用户工具

站点工具


编程:lua:capi:遍历

遍历数组

格式如下:

 int len=luaL_len(L,-1);
 for(int i=1;i<=len;i++){
     lua_rawgeti(L,-1,i);
     //do something...
     //此时数据位于-1位置
     lua_pop(L,1);
 }

遍历表

lua_pushnil(L);
while (lua_next(L, -2)) {
  // 此时栈上 -1 处为 value, -2 处为 key
  //do something...
  lua_pop(L, 1);
}

遍历 table 的过程中不要直接对处于 -2 位置的 key 做 lua_tostring 操作,除非你确信现在这个 key 就是字符串类型,否则下一次执行 lua_next 就等着意外吧。

编程/lua/capi/遍历.txt · 最后更改: 2019/08/08 22:56 由 cgoxopx