c++遍歴lua table例

1077 ワード

c/c++スタックからLuaスタックからのtableデータを取得
 
  
map traverse_table(lua_State *L, int index)
{
 map data;
    lua_pushnil(L);
    // :-1 => nil; index => table
 index = index - 1;
    while (lua_next(L, index))
    {
        // :-1 => value; -2 => key; index => table
        // key , lua_tostring key
        lua_pushvalue(L, -2);
        // :-1 => key; -2 => value; -3 => key; index => table

        const char* key = lua_tostring(L, -1);
        const char* value = lua_tostring(L, -2);

  data[key]=value;
        // value key, key lua_next
        lua_pop(L, 2);
        // :-1 => key; index => table
    }
    // :index => table ( lua_next 0 key )
    //
 return data;
}