lua-users home
lua-l archive

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


On Tuesday 15 June 2004 07:36 am, Jose Marin wrote:
> How to declare a function, in tolua, to get a Lua
> function as a parameter?
>
> This function will store the pointer, and call the
> function later.

Something like this, in the .pkg file:

$#define dummy_C_function(arg1) C_function(tolua_S, arg1)

void dummy_C_function @ C_function(LUA_VALUE arg1);

(With  Lua 5.0, lua_Object instead of LUA_VALUE also should work.)

The macro ensures that the function is passed the lua state. This is pretty 
ugly, but as of yet, there does not seem to be any other way to do this. The 
renaming trick with dummy_C_function is necessary, because otherwise the C 
preprocessor will also substitute the name of the binding function.

Then, in your C file, you do something like this:

void C_function(lua_State *L, int arg1)
{
  /* keep the reference to the function live after this function returns */
  lua_pushvalue(L, arg1); 
  int ref = lua_ref(L, 1);
  store(ref);   /* now store reference */
  ....
}

Don't forget to call lua_unref() when the lua function is no longer needed.

In Lua, you call the function simply: C_function(lua_function)

Hope this helps
- Christian