[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Functions with individual metatables
- From: Richard Hundt <richardhundt@...>
- Date: Tue, 19 May 2009 18:06:05 +0200
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