3.11 – Manipulating Tables
Tables are created by calling the function
- void lua_newtable (lua_State *L);
This function creates a new, empty table and pushes it onto the stack.
To read a value from a table that resides somewhere in the stack, call
- void lua_gettable (lua_State *L, int index);
where index
points to the table. lua_gettable
pops a key from the stack and returns (on the stack) the contents of the table at that key. The table is left where it was in the stack. As in Lua, this function may trigger a metamethod for the “index” event (see 2.8). To get the real value of any table key, without invoking any metamethod, use the raw version:
- void lua_rawget (lua_State *L, int index);
To store a value into a table that resides somewhere in the stack, you push the key and then the value onto the stack, and call
- void lua_settable (lua_State *L, int index);
where index
points to the table. lua_settable
pops from the stack both the key and the value. The table is left where it was in the stack. As in Lua, this operation may trigger a metamethod for the “settable” or “newindex” events. To set the real value of any table index, without invoking any metamethod, use the raw version:
- void lua_rawset (lua_State *L, int index);
You can traverse a table with the function
- int lua_next (lua_State *L, int index);
where index
points to the table to be traversed. The function pops a key from the stack, and pushes a key-value pair from the table (the “next” pair after the given key). If there are no more elements, then lua_next
returns 0 (and pushes nothing). Use a nil key to signal the start of a traversal.
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) {
- /* `key' is 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)));
- lua_pop(L, 1); /* removes `value'; keeps `key' for next iteration */
- }
While traversing a table, do not call lua_tostring
directly on a key, unless you know that the key is actually a string. Recall that lua_tostring
changes the value at the given index; this confuses the next call to lua_next
.