lua-users home
lua-l archive

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


Normally you will have two situations - registering a callback
function, and calling a callback function.

The registering function will generally take a function argument, and
store it somewhere. If the registering function is global, then one
approach is to use luaL_ref with the registry table. If the
registering function is on a userdata, then luaL_ref on the userdata
environment may be more appropriate. The integer return value of
luaL_ref is then remembered (by your C code) for later.

Calling a callback then involves calling lua_rawgeti with value
previously return by luaL_ref.

C code cannot hold a direct reference to the callback function, as the
Lua GC would not know about it, and thus might GC the function while
you hold a reference to it. Hence the standard approach is to put the
callback function in a table (like luaL_ref does) and then use
lua_rawgeti to quickly get it out of the table again.

On Thu, Jun 25, 2009 at 12:26 PM, Jose Marin<jose_marin2@yahoo.com.br> wrote:
>
> Hi.
>
> What's the best approach to use callbacks in Lua?
>
> For example, when the user clicks a mouse button, the Lua function 'mousebutton' must be called.
>
> One simple way of doing this is (syntax checking is off) :
>
> lua_pushstring(L, "mousebutton");
> lua_rawget(L, -1); // I will check the correct value
>
> if(lua_type(L, -1) == LUA_TFUNCTION )
> {
>    lua_pushinteger(L, ev.x);
>    lua_pushinteger(L, ev.y);
>    lua_pushinteger(L, ev.button);
>
>   lua_call(L, 3, 0);
> }
>
> lua_pop(L, 0);
>
> But would be nice if I stored the reference to the  'mousebutton' in C code to be called later, avoiding the 'lua_rawget' .
>
> I have not used Lua for a while, so I don't know if there is a more efficient way of doing this.
>
> How do you handle events in your game?
>
> Thanks
>
> Jose
>
>
>      Veja quais são os assuntos do momento no Yahoo! +Buscados
> http://br.maisbuscados.yahoo.com
>