Lua Garbage collector and weak tables Weak tables


Example

local t1, t2, t3, t4 = {}, {}, {}, {} -- Create 4 tables
local maintab = {t1, t2} -- Regular table, strong references to t1 and t2
local weaktab = setmetatable({t1, t2, t3, t4}, {__mode = 'v'}) -- table with weak references.

t1, t2, t3, t4 = nil, nil, nil, nil -- No more "strong" references to t3 and t4
print(#maintab, #weaktab) --> 2 4

collectgarbage() -- Destroy t3 and t4 and delete weak links to them.
print(#maintab, #weaktab) --> 2 2