假設table的在stack中的索引位置爲index,如今從C代碼裏面對這個lua的table進行遍歷,方法以下:html
方法一、當index爲正值的時候,可用以下代碼:this
注意:t>0
lua
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); } }
方法二、index爲任意狀況:code
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_nexthtm
http://stackoverflow.com/questions/6137684/iterate-through-lua-table索引
http://stackoverflow.com/questions/1438842/iterating-through-a-lua-table-from-crem