[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Res: Event callbacks
- From: Jose Marin <jose_marin2@...>
- Date: Thu, 25 Jun 2009 05:22:59 -0700 (PDT)
I think that would be faster to store the reference to the function using lua_rawset at LUA_GLOBALSINDEX, and then, when needed, use lua_rawgeti (as you suggested) to retrieve the reference to the function, right?
----- Mensagem original ----
De: Peter Cawley <email@example.com>
Para: Lua list <firstname.lastname@example.org>
Enviadas: Quinta-feira, 25 de Junho de 2009 8:38:06
Assunto: Re: Event callbacks
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<email@example.com> wrote:
> 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?
> Veja quais são os assuntos do momento no Yahoo! +Buscados
Veja quais são os assuntos do momento no Yahoo! +Buscados