当前位置: 移动技术网 > IT编程>脚本编程>Lua > Lua 学习笔记之C API 遍历 Table实现代码

Lua 学习笔记之C API 遍历 Table实现代码

2017年12月08日  | 移动技术网IT编程  | 我要评论

lua 通过一个虚拟栈与 c 的交互,正数索引自底向上取值,负数索引自顶向下取值。

lua 中的 table(表)结构可以使用任何数据作为 key 进行取值。使用 c api 访问 table 中的元素有两种方法:

复制代码 代码如下:

lua_getglobal(l, t);
lua_pushinteger(l, k); -- 这里可以换成其它类型的 lua_pushxxxx(l, k) 压数据到栈顶作key
lua_gettable(l, -2);

lua_getglobal(l, t);
lua_getfield(l, -1, k);

在结束时,栈上的情况均为:栈顶为 t[k],次顶元素为 table 类型的 t。第二种方法其实是第一种方法在「key 为字符串」时的特殊写法。

c api 遍历 table

复制代码 代码如下:

lua_getglobal(l, t);
lua_pushnil(l);
while (lua_next(l, -2)) {
/* 此时栈上 -1 处为 value, -2 处为 key */
lua_pop(l, 1);
}

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

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

虽然这是中记载的遍历方法,但这种方法在遍历时并没有一定的遍历顺序,于是便又有了下面的方法。

用整数 key 进行并不那么完美的遍历

复制代码 代码如下:

lua_getglobal(l, t);
len = lua_objlen(l, -1);
for (i = 1; i <= len; i++) {
    lua_pushinteger(l, i);
    lua_gettable(l, -2);
    /* 此时栈顶即为 t[i] 元素 */
    lua_pop(l, 1);
}

这种方法无视了非整数 key,但可以保证遍历顺序。如果只关注整数 key,可以考虑用这种遍历方法 :)

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网