lua-users home
lua-l archive

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


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