lua-users home
lua-l archive

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


Mark> A way to tear off new copies of a function would definitely be useful.

If you mean creating new closures sharing the same code, then it's pretty
simple. Here is a quick hack (little tested, bad name). It "clones" the
Lua function on top of the stack and leaves there a new closure with the
same code and nil for all upvalues.

LUA_API void lua_clonefunction (lua_State *L) {
  TValue *o;
  lua_lock(L);
  api_checknelems(L, 1);
  o = L->top - 1;
  if (isLfunction(o)) {
    Proto *tf = clvalue(o)->l.p;
    Closure *cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
    int i;
    cl->l.p = tf;
    incr_top(L);
    for (i = 0; i < tf->nups; i++)
      cl->l.upvals[i] = luaF_newupval(L);
    incr_top(L);
    setclvalue(L, L->top - 1, cl);
  }
}

Whether it should remove the old function from the stack or copy the upvalues
and what to do about errors is left for further work... Also, I don't mean
to suggest that will make into a future version of Lua...

David> I agree with this. My issue is that I am potentially operating in a
David> memory constrained environment and I would rather avoid the
David> multiple copies of the functions in each thread.

Alas, the code above won't help you with that because the clones must
reside in the same Lua thread.

--lhf