Lua C API 遍历 table

 

http://timothyqiu.com/archives/lua-note-table-traversal-using-c-api/

 

C API 遍历 Table

1 lua_getglobal(L, t);
2 int index = lua_gettop(L);
3 lua_pushnil(L);
4 while (lua_next(L, index)) {
5     /* 此时栈上 -1 处为 value, -2 处为 key */
6     lua_pop(L, 1);
7 }

 

lua_next 函数针对 -2 处(参数指定)的 Table 进行遍历。弹出 -1 处(栈顶)的值作为上一个 key(为 nil 时视为请求首个 key),压入 Table 中的下一个 key 和 value。返回值表示是否存在下一个 key。

lua_next 原理详解

另外在循环中处理值时要记得随时清理栈,否则 Table 就不在 -2 了。(也可以考虑在 lua_getglobal 后用lua_gettop 存下 Table 的正数索引。)

 

posted on 2016-02-16 14:12  明天有风吹  阅读(1377)  评论(0编辑  收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园