C luaを巡るtable

2125 ワード

tableのstackにおけるインデックス位置がindexであると仮定し、このluaのtableをCコードから遍歴する方法は以下の通りである.
方法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
",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
", 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