Lua访问表的键和值

时间:2012-09-15 21:03:51

标签: c++ lua lua-table

我想在关卡编辑器中读取Lua文件,以便以可视格式显示其数据,供用户编辑。

如果我有这样的Lua表:

properties = {
  Speed = 10,
  TurnSpeed = 5
}

Speed显然是关键值10。我知道如果我知道密钥就可以访问该值(如果表已经在堆栈中):

lua_pushstring(L, "Speed");
lua_gettable(L, idx); 
int Speed = lua_tointeger(L, -1);
lua_pop(L, 1); 

我想要做的是在C ++中访问密钥的名称和相应的值。可以这样做吗?如果是这样我该怎么办呢?

1 个答案:

答案 0 :(得分:4)

这由lua_next function涵盖,它迭代表的元素:

// table is in the stack at index 't'
lua_pushnil(L);  // first key
while (lua_next(L, t) != 0)
{
  // uses 'key' (at index -2) and 'value' (at index -1)
  printf("%s - %s\n", luaL_typename(L, -2), luaL_typename(L, -1));
  // removes 'value'; keeps 'key' for next iteration
  lua_pop(L, 1);
}

lua_next键离开表的键,因此您需要在迭代时将其保留在堆栈中。每个调用都将跳转到下一个键/值对。一旦它返回0,那么你就完成了(当弹出键时,下一个键没有按下)。

显然,向正在迭代的表中添加或删除元素可能会导致问题。

相关问题