lua-users home
lua-l archive

Re: Saving Lua Function and Call Later in C?

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


>> 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
> work.
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);
 switch (t)
 {
 case LUA_TFUNCTION: /* function */
 // What to save here so lua_callback() function to call.
luaL_ref? lua_topointer?
 // setup callback
 lua_pushvalue(L, index);
 int ref = luaL_ref(L, LUA_REGISTRYINDEX);
 /* store int somewhere*/
 break;
 }
/* 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)
{
 lua_unref(L, ref);
}
Alexander.

AltStyle によって変換されたページ (->オリジナル) /