How do I traverse a Lua table?

Traversing a general table uses lua_next. This code is the equivalent of using 'pairs' in Lua:

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

To go over the elements of an array, use lua_rawgeti. This is the fastest form of array access, since no metamethods will be checked.

For example, this function makes a copy of a table passed as its argument:

static int l_copy(lua_State *L) {
 // the table is at 1
 int i,n = lua_objlen(L,1); // also works for strings, equivalent of #
 lua_createtable(L,n,0); // push our new table, with explicit array size
 for (i = 1; i<=n; i++) {
 lua_rawgeti(L,1,i);
 lua_rawseti(L,-2,i); // value is at -1, new table is at -2
 }
 return 1; // new table remains on stack
}



Back