这里会显示出您选择的修订版和当前版本之间的差别。
两侧同时换到之前的修订记录 前一修订版 | |||
编程:lua:capi:遍历 [2019/08/08 22:49] cgoxopx 编程:lua:遍历 更名为 编程:lua:capi:遍历 |
编程:lua:capi:遍历 [2019/08/08 22:56] (当前版本) cgoxopx |
||
---|---|---|---|
行 1: | 行 1: | ||
- | ====== lua遍历数组 ====== | + | ====== 遍历数组 ====== |
格式如下:\\ | 格式如下:\\ | ||
- | int len=luaL_len(L,-1); | + | int len=luaL_len(L,-1); |
- | for(int i=1;i<=len;i++){ | + | for(int i=1;i<=len;i++){ |
- | lua_rawgeti(L,-1,i); | + | lua_rawgeti(L,-1,i); |
- | //do something... | + | //do something... |
- | lua_pop(L,1); | + | //此时数据位于-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 就等着意外吧。 |