views:

685

answers:

3

In Lua, using the C interface, given a table, how do I iterate through the table's key/value pairs?

Also, if some table table members are added using arrays, do I need a separate loop to iterate through those as well or is there a single way to iterate though those members at the same time as the key/value pairs?

+3  A: 

lua_next() is just the same as Lua's next() function, which is used by the pairs() function. It iterates all the members, both in the array part and the hash part.

If you want the analogue of ipairs(), the lua_objlen() gives you the same functionality as #. Use it and lua_rawgeti() to numerically iterate over the array part.

Javier
+5  A: 

As Javier says, you want the lua_next() function. I thought a code sample might help make things clearer since this can be a little tricky to use at first glance.

Quoting from the manual:

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);
}

Be aware that lua_next() is very sensitive to the key value left on the stack. Do not call lua_tolstring() on the key unless it really is already a string because that function will replace the value it converts.

RBerteig
A: 

This is the second time I've come back here to see how to do this - Thanks Javier and RBerteig! One small thing: After the initial lua_pushnil(L) call, the table is actually at 't-1', not 't' like it shows in the example.

BStep