lua-users home
lua-l archive

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


On Tue, Apr 10, 2007 at 08:35:26PM +0200, Olivier Galibert wrote:
> On Tue, Apr 10, 2007 at 11:22:25AM -0700, Jose Marin wrote:
> > But justo to increase my knowledge on Lua, it's possible to save the result of lua_getglobal(L, "OnTimer"); ?

Yes and no. The only place you can save it is a lua table, or the lua
stack. You are attempting to avoid calling getglobal(), though, because
its a table lookup.

> int cb;
> 
> > This way, on the beggining of the game I could do this
> > 
> > lua_getglobal(L, "OnTimer");

int OnTimeIndex = lua_gettop(L);

It is "saved" here, its on the lua_State's stack. If you never pop it,
it will always be at index OnTimeIndex.

If you less than a few dozen callbacks, this is simple to do. With lots
of callbacks, you are maintaining a huge stack. Does that matter in lua?
No idea, though you might have to tell lua to grow the stack.

> > SaveFunctionOnStack(L, FUNC_ONTIMER);
> 
> cb = luaL_ref(L, LUA_REGISTRYINDEX);

There are two kinds of table lookups - through the hash part of a table,
or the array part. This is transparent from a behaviour but not
performance point of view, so its worth knowing the distinction exists.

What using luaL_ref() does is basically transform a lookup of a string
in the "hash" part of a predefined table to a lookup of a number in
(hopefully) the array portion of a (different) predefined table.

"hopefully", because its not clear to me that the reference system
*guarantees* that all references will stay in the array part of a table.
If it doesn't guarantee this, using references will devolve to a hash
table lookup of a number, which is what you appear to be trying to avoid
in the first place.

Also, after you lua_call() your callback function, everything it does
(almost) will involve table lookups - functions stored in global tables,
global variable access, metafunction access. In terms of increasing your
lua knowledge, starting coding with the assumption that lua's table
access is slow enough it needs to be optimized around might not be a
good idea, pretty much everything except local variable access
uses table lookups in lua.

Cheers,
Sam

> > 
> > FUNC_ONTIMER it's an index on an array, where the reference to Lua funcsions would be saved.
> > 
> > Then, the evente handler would be like this:
> > 
> >      case WM_TIMER:
> >          PushFunctionToStack(L, FUNC_ONTIMER); // Just takes the contents of the array at position FUNC_ONTIMER and pushes it on the Lua stack
> 
> lua_rawgeti(L, LUA_REGISTRYINDEX, cb);
> 
> > 
> >          lua_pushnumber(L, wParam);
> > 
> >          lua_call(L, 1, 0);
> > 
> >         break;
> 
>   OG.