假设table的在stack中的索引位置为index,现在从C代码里面对这个lua的table进行遍历,方法如下:
方法1、当index为正值的时候,可用如下代码:
注意:t>0
void printtb(lua_State *L,int index)
{
/* table is in the stack at index 'index' */
lua_pushnil(L); /* first key 如果index是负数,此时table的索引位置变化了:假如原来是-1,现在变成-2了*/
while (lua_next(L, index) != 0) {
/* uses 'key' (at index -2) and 'value' (at index -1) */
printf("%s - %s\n",lua_tostring(L, -1), lua_tostring(L, -2));
//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);
}
}
方法2、index为任意情况:
static void iterate_and_print(lua_State *L, int index)
{
// Push another reference to the table on top of the stack (so we know
// where it is, and this function can work for negative, positive and
// pseudo indices
lua_pushvalue(L, index);
// stack now contains: -1 => table
lua_pushnil(L);
// stack now contains: -1 => nil; -2 => table
while (lua_next(L, -2))
{
// stack now contains: -1 => value; -2 => key; -3 => table
// copy the key so that lua_tostring does not modify the original
lua_pushvalue(L, -2);
// stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
printf("%s => %s\n", lua_tostring(L, -1), lua_tostring(L, -2));
// pop value + copy of key, leaving original key
lua_pop(L, 2);
// stack now contains: -1 => key; -2 => table
}
// stack now contains: -1 => table (when lua_next returns 0 it pops the key
// but does not push anything.)
// Pop table
lua_pop(L, 1);
// Stack is now the same as it was on entry to this function
}
参考:
http://www.lua.org/manual/5.2/manual.html#lua_next
http://stackoverflow.com/questions/6137684/iterate-through-lua-table
http://stackoverflow.com/questions/1438842/iterating-through-a-lua-table-from-c