lua-users home
lua-l archive

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




On Fri, Dec 12, 2008 at 8:34 AM, Alexander Gladysh <agladysh@gmail.com> wrote:
Robert,

> 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.

Thanks Alexander, I had some time this morning and thought I'd let you sleep :) and ask the list.

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?

Anyway, I look forward to the code later.  Back to less interesting stuff at work.