Weak Tables
local t = {}
setmetatable(t, {__mode = 'k'})
do
-- closure
local key = {} -- key is the reference to this table (object)
t[key] = 123
end
collectgarbage() -- force a garbage collection cycle
-- variable 'key' is out of scope since it was created in a closure
-- after garbage collection, the object held by key is removed from 't'
for k, v in pairs(t) do
print(k, v)
end
-- prints nothing
do
key = {}
t[key] = 123
end
collectgarbage()
-- key is still valid since it's a global variable
for k, v in pairs(t) do
print(k, v)
end
-- prints table: 0x56144f2e36e0 123Last updated