lua-users home
lua-l archive

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


> I don't agree with this. In this particular case, for example, a
> finalizer for the table allowed you to use the table as a wrapper for a
> userdata. Without the ability to create a finalizer for the table, you
> are forced to use a SECOND userdata as a wrapper to the userdata. In
> general I'd rather work with tables than userdata when I can.

Ummm... You could just attach the __gc method to the userdata and just use
it rather than wrapping it. It is useful to attach tables to userdata as
well, but that can be done in at least two ways:

1) Use the metatable. This has the disadvantage that you cannot also verify
the "type" of the metatable, although there are ways around that (like
locking the metatable).

2) Use a weak-keyed table keyed by the userdata.

Your example of lazy serialising of expensive computations is interesting,
though. This finally gave me a chance to experiment with newproxy, although
I'm not convinced that it is the best mechanism for this.

I wanted to write this so the finaliser could be attached to any object,
but I haven't yet figured out how to make the proxy outlive the object and
still be able to reference it.

(A very strange Hello, world example)

gentoo lua-5.0 # bin/lua
Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
>   function register_finaliser(obj, final)
>>     local proxy = newproxy(true)
>>     local meta = getmetatable(proxy)
>>     function meta:__gc()
>>       final(obj)
>>     end
>>     meta.__index = obj
>>     meta.__newindex = obj
>>     return proxy
>>   end
>
>   function final(t) print(t.msg) end
>
>   a = register_finaliser({msg = "Hello, world"}, final)
>
>   a = nil
>   collectgarbage()
Hello, world