ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## lua_next lua_next(L,index):先把 表(lua栈 index所指的表), 的当前索引弹出,再把table 当前索引的值弹出,也就是先弹出 table的索引,再弹出table索引的值 举例: ``` local t = { ["a"] = 1, ["b"] = 2, ["c"] = 3 } ``` 使用`lua_next`遍历table `t` ```c int traversing(lua_State *L) { lua_pushnil(L); /*此时栈的状态 ------- | -1 nil | -2 table NUMBER_TABLE ------- */ while (lua_next(L, -2)) { /*此时栈的状态 ------- | -1 value | -2 key | -3 table NUMBER_TABLE ------- */ if (lua_isnumber(L, -2)) printf("nkey: %d\t", luaL_checkinteger(L, -2)); else if (lua_isstring(L, -2)) printf("skey: %s\t", luaL_checkstring(L, -2)); if (lua_isnumber(L, -1)) printf("nvalue: %d\t", luaL_checkinteger(L, -1)); else if (lua_isstring(L, -1)) printf("svalue: %s\t", luaL_checkstring(L, -1)); /*此时栈的状态 ------- | -1 value | -2 key | -3 table NUMBER_TABLE ------- */ lua_pop(L, 1); /*此时栈的状态 ------- | -1 key | -2 table NUMBER_TABLE ------- */ } lua_pop(L, 1); /*此时栈的状态 ------- | -1 table NUMBER_TABLE ------- */ return 0; } ``` lua_next(L, -2) 这个函数的工作过程是: 1) 先从栈顶弹出一个 `key` 2) 从栈指定位置的 `table` 里取下一对 key-value,先将 `key` 入栈,再将 `value` 入栈 3) 如果第 2 步成功则返回非 0 值,否则返回 0,并且不向栈中压入任何值, 第 2 步中从 `table` 里取出"下一对 `key-value`"是相对于第 1 步中弹出的 key 的。`table` 里第一对 `key-value` 的前面没有数据,所以先用 `lua_pushnil()` 压入一个 `nil` 充当初始 `key`。 https://blog.csdn.net/mydreamremindme/article/details/47702901