lua-users home
lua-l archive

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


> I've got a C program that Lua could return a function to and I'd like to
> save that function to call later when an event occurs.  What do I need to
> save so I can call the function?  How do I call the function?
> Here is some example code I hope clarifys things:
> --------------------
> 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
>       break;
>     case LUA_TSTRING:  /* strings */
>       value = lua_tostring(L, index);
>       break;
>     ...
> }
> static int lua_callback()
> {
>   // call the function staved in get_value_from_lua()
> }

Never use lua_topointer() except for debugging purposes (like
conversion of arbitrary data to string like Lua tostring() does.).

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.