[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Saving Lua Function and Call Later in C?
- From: "Alexander Gladysh" <agladysh@...>
- Date: Sat, 13 Dec 2008 02:25:19 +0300
>> You have to store Lua value of a function in a registry with
>> luaL_ref(). Store integer that luaL_ref() returns.
>> When callback is called, it should be called with that integer. Fetch
>> stored value from registry and call it.
>> When you no longer need to store the value of function (in general
>> this is not the same moment as the function is called), you remove its
>> value from the registry.
>> I would post some code this evening.
> I thought I'd use luaL_ref, keep a struct for callback information. But I
> was missing another bit of information. luaL_ref() pops a value off the
> stack but I'm not popping the stack, just looping through it. So do I need
> to change my loop to pop or do some dance to move the function to the top of
> the stack pop it using luaL_ref() then put it back where it was?
Use lua_pushvalue() to push value already on stack.
> Anyway, I look forward to the code later. Back to less interesting stuff at
Something along these lines (pseudocode). Tell me (off the list) if
you need actually working code.
static void get_value_from_lua(lua_State *L, int index)
t = lua_type(L, index);
case LUA_TFUNCTION: /* function */
// What to save here so lua_callback() function to call.
// setup callback
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
/* store int somewhere*/
/* How you get EXTRA_ARGS depends on the implementation */
static int lua_callback(lua_State * L, int ref, EXTRA_ARGS)
lua_rawgeti(L, ref); /* push stored function */
int nargs = /* Number of EXTRA_ARGS */;
/* ...push EXTRA_ARGS to stack... */
/* call function (error checking omitted) */
lua_pcall(L, nargs, LUA_MULTRET);
/* Process results */
static int collect_callback(lua_State * L, int ref)