[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: anti...require?
- From: steve donovan <steve.j.donovan@...>
- Date: Mon, 2 Feb 2009 11:17:41 +0200
On Sat, Jan 31, 2009 at 6:33 PM, Luiz Henrique de Figueiredo
<lhf@tecgraf.puc-rio.br> wrote:
> You cannot set __gc for tables. But you can say use a udata as upvalue for
> all functions registered in the module and then clean up when that udata
> is collected.
>
This shows a little module that encapsulates this pattern:
-- atend.lua
local obj = newproxy(true)
local mt = getmetatable(obj)
local atend_list = {}
mt.__gc = function()
for _,fun in ipairs(atend_list) do
fun()
end
end
mt.__call = function(obj,fun)
table.insert(atend_list,fun)
end
return obj
Then, to add finalization code to any module, do this:
require('atend')(function()
-- any finalization code for this module
print "finis"
end)
I've tested this with a few modules and things work as expected. Note
that it requires the undocumented function newproxy to make a
zero-length userdata (the garbage-collect metamethod __gc doesn't work
for regular tables)
steve d.