lua-users home
lua-l archive

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


Henk Boom wrote:


This doesn't work transparently, though, you have to be careful when
using this implementation as it will introduce memory leaks in the
presence of cycles.


Nice catch.

Since I've posted the code, I now feel obligated to maintain it :)

So I've given it a bit more thought, fixed some bugs in my previous post and simplified it. It'll still suffer the same leak with cycles, but these can now be factored out so:

setfmeta(f, {__index = function () return f end})

becomes:

setfmeta(f, {__index = function(t, k) return t.func end})

and the code:

local func_meta = { }
setmetatable(func_meta, { __mode = "k" })

debug.setmetatable(function() end, {
   __index = function(func, key)
      local meta = func_meta[func]
      if meta then
         return meta[key]
      end
   end;
   __newindex = function(func, key, val)
      local meta = func_meta[func]
      if meta then
         meta[key] = val
      end
   end;
})

function setfmeta(func, meta)
   func_meta[func] = setmetatable({ func = func }, meta)
   return func
end

function getfmeta(func)
   return getmetatable(func_meta[func])
end

Cheers,
Rich