lua-users home
lua-l archive

Faster C API table traversion?

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


Hi list,

is there a faster way of doing the following basic search, i.e. can the traversal of the table be made more efficient? Specifically, using something other than lua_next() maybe?

This below is by the book, based on the manual [1]:

static int search(lua_State *L, int idx, char* needle) {

int not_found = 1;
int type = lua_type(L, idx);

if(type == LUA_TTABLE) {
lua_pushnil(L);
while (not_found && lua_next(L, idx) != 0) {
not_found = search(L, idx+2);
lua_pop(L, 1);
}
lua_pop(L, 1);
}
else if(type == LUA_TSTRING) {
const char *hay = lua_tostring(L, idx);
not_found = inspect(hay, needle);
}
return not_found;
}

The source is abbreviated and not tested in the exact way listed above, so if there should be a syntax flaw, my bad. But it's about the usage of the Lua API.

Thanks a lot,
Henning

[1] http://www.lua.org/manual/5.1/manual.html#lua_next :
"A typical traversal looks like this:

/* table is in the stack at index 't' */
lua_pushnil(L); /* first key */
while (lua_next(L, t) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",
lua_typename(L, lua_type(L, -2)),
lua_typename(L, lua_type(L, -1)));
/* removes 'value'; keeps 'key' for next iteration */
lua_pop(L, 1);
}"

AltStyle によって変換されたページ (->オリジナル) /