lua-users home
lua-l archive

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


Mike,
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
idea.
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.

Bye,
--Leo--

On 8/14/06, Mike Pall <mikelu-0608@mike.de> wrote:
Hi,

slonik.az@gmail.com 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).

Bye,
     Mike