[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Table traversal
- From: Roberto Ierusalimschy <roberto@...>
- Date: Thu, 29 Jul 1999 14:20:48 -0300
> In Lua 3.2, the lua.h file contains a lua_next function. This looks like
> the Lua next function for traversing tables, but it's API isn't very
> clear. (I can't find it in the docs.)
We put this function, but we are still not sure whether we will keep it;
that's why it has no docs.
Its typical use is something like
lua_Object table = getyourtable();
int i = 0;
do {
lua_beginblock();
i = lua_next(table, i);
if (i) {
lua_Object index = lua_getresult(1);
lua_Object value = lua_getresult(2);
... /* use index-value for whatever you need */
}
lua_endblock();
} while (i);
(warning: a common bug is to change the if to "if (!i) break;" and then
do not call the last "lua_endblock"). That is, "i" is an index with
only internal significance, that must start with 0, be passed from one
call to the next, and when it is 0 the traverse is over. For each call
to lua_next with return not 0, the results (index and value) are in lua2C.
With that code, you can traverse a table in an efficient way, without
the problem of how to keep the indices from one iteration to the next
accross different blocks.
-- Roberto
PS: the reason we are not very happy with this API is that it is not easy
to implement the builtin "next" function using "lua_next" :-(