lua-users home
lua-l archive

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


function functionfactory()
   local upvalue1, upvalue2
   return function()
       return upvalue1 + upvalue2
   end
end

local clone1 = setfenv(functionfactory(), env1)
local clone2 = setfenv(functionfactory(), env2)

clone1 and clone2 now shares prototype and upvalues, but have different environments
Is this what you meant?

On Mon, Jun 21, 2010 at 2:32 PM, Jerome Vuarand <jerome.vuarand@gmail.com> wrote:
2010/6/21 Chaos Wang <chaoslawful@gmail.com>:
> 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.