[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: moving a lua array to C
- From: "Wim Couwenberg" <w.couwenberg@...>
- Date: Tue, 11 Mar 2003 16:42:47 +0100
> One
> way would be to count the elements first then copy them but then I'd
> be doing two times the needed work. Is there a better(faster/cleaner)
> way to do this?
Getting the number of entries _is_ cheap:
Lua 4: lua_getn(L, index); /* index of table in stack */
In Lua 5 getn is no longer in the C API but it is available as table.getn in
the base lib: (sample code w/o checking of any kind :-)
/* get "table" table */
lua_pushstring(L, "table");
lua_gettable(L, LUA_GLOBALSINDEX);
/* get "getn" entry */
lua_pushstring(L, "getn");
lua_gettable(L, -2);
/* call it and get result */
lua_pushvalue(L, index); /* index of your table in the stack */
lua_call(L, 1, 1);
n_elements = lua_tonumber(L, -1); /* store table size */
lua_pop(L, 1); /* pop table size */
Of course you can also keep a private reference to the getn function instead
of constantly looking it up in the globals (e.g. in the lua registry.)
Yet another possibility is to start with a small C array and doubling its
size whenever it would overflow. Adding values to your array this way is
still a (amortized) constant time operation, i.e. cheap.
Bye,
Wim