Weak Tables
Lua's way of memory management is running something called a garbage collector. Every garbage collection cycle, all objects that have no references is freed back up to use to the program. Weak tables are a way to let the garbage collector know that it can go ahead and free up the memory if there are no references to that object anymore.
The weakness of a table is set by the __mode metamethod, if the string of __mode contains k, the keys are weak. If it contains v, the values are weak. If it contains both (kv), both the keys and values are considered weak.
Example:
1
local t = {}
2
​
3
setmetatable(t, {__mode = 'k'})
4
​
5
do
6
-- closure
7
local key = {} -- key is the reference to this table (object)
8
t[key] = 123
9
end
10
​
11
collectgarbage() -- force a garbage collection cycle
12
-- variable 'key' is out of scope since it was created in a closure
13
-- after garbage collection, the object held by key is removed from 't'
14
​
15
for k, v in pairs(t) do
16
print(k, v)
17
end
18
​
19
-- prints nothing
20
​
21
do
22
key = {}
23
t[key] = 123
24
end
25
​
26
collectgarbage()
27
-- key is still valid since it's a global variable
28
​
29
for k, v in pairs(t) do
30
print(k, v)
31
end
32
​
33
-- prints table: 0x56144f2e36e0 123
Copied!
Last modified 2yr ago
Copy link