In a weak-keyed table, lthough the key is held weakly, the value is
held strongly. This is more or less what you want, except that if the
value has a reference (directly or not) to the key, this is enough to
'anchor' the key and stop it from being collected. Even once the key,
'object' in this case, is no longer referenced from anywhere external,
the _private table still holds onto it because it is referenced from
the value. Lua 5.2 changes this so that the references from table
values "don't count" for keeping the key around. (google up 'ephemeron
tables' for more info)
An often overlooked example of an indirect reference, adapted from
uki's example:
local _M = {}
-- stolen from: https://github.com/kikito/middleclass/wiki/Private-stuff
local _private = setmetatable({}, {__mode = "k"})
--constructor
function _M:new(...)
local object = {position = {4, 6}}
-- do stuff
_private[object].draw_closure = function ()
draw_point_at(object.position)
end
return object
end
draw_closure is a closure which keeps a reference to 'object' as an
upvalue, and this is enough to keep it from being collected.
henk