lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 30/04/2011 21.59, Henk Boom wrote:
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:
local _private = setmetatable({}, {__mode = "k"})

function _M:new(...)
   local object = {position = {4, 6}}
    -- do stuff

   _private[object].draw_closure = function ()
   return object

draw_closure is a closure which keeps a reference to 'object' as an
upvalue, and this is enough to keep it from being collected.


To Mark & Henk:

Thank you very much for the detailed explanations.

Although I'm no expert of garbage collector's operations (I never used weak or semi-weak tables and only skimmed on the subject when reading the manual), now the issue is clear enough to make sense to me.