[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: How two C-closures can share an upvalue??
- From: slonik.az@...
- Date: Mon, 14 Aug 2006 07:57:22 -0400
thanks a lot for your reply!!
Using Function Environment in C (lua_getfenv/lua_setfenv) to share a
table between any subset of C-closures in a module is a very clever
The added bonus is the fact that Lua table can have its own metatable
that can define __gc metamethod to clean up the resources when this
shared pool of information is not need anymore. This could happen when
all the closures that share this table go out of scope.
On 8/14/06, Mike Pall <firstname.lastname@example.org> wrote:
> Lua closures can share their private state with each other by sharing
> their "outer local" variables. [...]
> I would like to achieve the same effect using C-closures. But I cannot
> figure out how?
Lua closures and C closures look similar, but the implementation
of upvalues is completely different. C upvalues are tagged
values. Lua upvalues are (basically) pointers to tagged values.
Only the latter can be shared.
But you can use a Lua table as a common upvalue for different C
closures and keep the values to be shared in the table.
An example of this is in the Lua I/O library (src/liolib.c) where
the C function environment table is shared amongst all functions.
Note that the C function environment table works just like an
additional upvalue (except that it can only be a table).
If you aren't creating multiple closures for each C function then
you might as well share values via the registry (a common table
accessible only by C functions).