lua-users home
lua-l archive

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

Jerome Vuarand wrote:
2010/6/21 Chaos Wang <>:
I wonder if there is any way to clone a Lua closure, where the clones share
the same Proto and upvalues but have different environment tables?

I tried lua_pushvalue(), but it only make a direct reference for GC-able
object (which includes closures), so there can't be different environment
tables coexisted.

Any ideas?
In Lua 5.1 you cannot clone a Lua closure that way. If the closure is
written in Lua, you can dump its byte code to a string and recompile
it, but upvalues won't be shared. The best you can do is compiling
several functions with the same code, and shared upvalues, into
several closures, by the way of source or byte code manipulation.

IIRC in Lua 5.2 I think you will be able to make two closures share
the same upvalues, so this could solve your problem.

In the meantime, you can expose us the real problem, and we may find
another solution than closure cloning.

PS: Your first email with the same questions went through (like you
could have verified in the mailing list archives). If you didn't get
any answer it's because there is no solution to your problem.


Sorry for that...

I'm trying to integrate LuaJIT with NginX, with each HTTP request handled by a individual coroutine.

For now I'm not considering coroutine support in user code, and using the following way to share user code between coroutines:
  1. create main coroutine
  2. load lua code in main coroutine, the closure's default env table is main coroutine's globals table
  3. create new coroutine to handle new request, make its globals table inherit main coroutine's globals table
  4. make a reference to lua code closure in new coroutine and resume it
  5. repeat 3,4 if there're more requests
This way the lua code has only to be loaded once, but all globals directly referenced to main coroutine's globals table, and module system doesn't work in new coroutine as module symbols will go into new coroutine's globals table instead of main coroutine's.

I think if lua closure can be copyed into new coroutine instead of make a reference only, then closures in different coroutines could have their env table set to the host coroutine's globals table, and the former problems will all be resolved easily.