lua-users home
lua-l archive

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


On 2/26/07, Graham Wakefield <lists@grahamwakefield.net> wrote:
Hi,

Is it possible to make a duplicate of a function in the C API?

I believe the following should work:

/* cfunction envtable -- newcfunction */
int makedupenv(lua_State * L)
{
 lua_CFunction f = lua_tocfunction(L, 1);
 luaL_argcheck(L, f != 0, 1, "expected C function");
 luaL_checktable(L, 2, LUA_TTABLE);
 /* note that the copy will not have any upvalues, even if the original does */
 lua_pushcfunction(L, f);
 lua_pushvalue(L, 1);
 lua_setfenv(L, 1);
 return 1;
}

You can use lua_getupvalue() to duplicate the C function with all its upvalues.

    -Mark