SunnyDay的专栏

假设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 indiceslua_pushvalue(L, index);// stack now contains: -1 => tablelua_pushnil(L);// stack now contains: -1 => nil; -2 => tablewhile (lua_next(L, -2)){// stack now contains: -1 => value; -2 => key; -3 => table// copy the key so that lua_tostring does not modify the originallua_pushvalue(L, -2);// stack now contains: -1 => key; -2 => value; -3 => key; -4 => tableprintf("%s => %s\n", lua_tostring(L, -1), lua_tostring(L, -2));// pop value + copy of key, leaving original keylua_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 tablelua_pop(L, 1);// Stack is now the same as it was on entry to this function}参考:

有理想在的地方,地狱就是天堂

SunnyDay的专栏

相关文章:

你感兴趣的文章:

标签云: