遍历Lua表

如何解决遍历Lua表

| 我正在尝试通过lua表进行迭代,但我一直收到此错误:
invalid key to \'next\'
我知道索引从-8开始,并且我知道那里有一个表,因为它得到了第一个(也是唯一的)值。但是,即使我知道表中只有一个字符串,它也会尝试再次循环。
if (lua_istable(L,index))
{
    lua_pushnil(L);

    // This is needed for it to even get the first value
    index--;

    while (lua_next(L,index) != 0)
    {
        const char *item = luaL_checkstring(L,-1);
        lua_pop(L,1);

        printf(\"%s\\n\",item);
    }
}
else
{
    luaL_typerror(L,index,\"string table\");
}
任何帮助,将不胜感激。 当我使用正索引(只要不从中删除1)时,这种方法就可以正常工作 编辑:我注意到,如果我不理会item的值,我不会得到此错误。仅当我开始读取item的值时,才会出现此错误。当我从表中获得值时,我调用了另一个Lua函数,这是否会破坏lua_next?     

解决方法

请勿将
luaL_checkstring
与否定参数一起使用。请改用
lua_tostring
。 另外,在循环中调用函数后,请确保堆栈保持不变:
lua_next
期望上一个表键位于堆栈顶部,以便它可以继续遍历。     ,您需要注意两件事: 确保在下次调用
lua_next
之前将原始密钥留在堆栈上。
luaL_checkstring
将非字符串键转换为字符串(由于结果字符串不在表中,因此它将成为无效键。)通过This2 by传递键的副本而不是原始键来实现,这很容易做到。 确保在每次循环中保留堆栈结构(即,按入弹出数量的值) 您的函数仅适用于
index
的负值。您正确地相信
index--;
将确保在按下键后
index
仍指向表,但是仅当
index
为负(即相对于堆栈顶部)时。如果
index
是绝对或伪索引,则它将导致它指向错误的项目。最简单的解决方法是将对该表的另一个引用推入堆栈的顶部。 这是一个用于演示的最小C程序:
#include <lauxlib.h>
#include <lua.h>

static void iterate_and_print(lua_State *L,int index);

int main(int ac,char **av)
{
   lua_State *L = luaL_newstate();
   luaL_openlibs(L);

   // Create a table and put it on the top of the stack
   luaL_loadstring(L,\"return {one=1,[2]=\'two\',three=3}\");
   lua_call(L,1);

   iterate_and_print(L,-1);
   return 0;
}

static void iterate_and_print(lua_State *L,int index)
{
    // Push another reference to the table on top of the stack (so we know
    // where it is,and this function can work for negative,positive and
    // pseudo indices
    lua_pushvalue(L,index);
    // stack now contains: -1 => table
    lua_pushnil(L);
    // stack now contains: -1 => nil; -2 => table
    while (lua_next(L,-2))
    {
        // stack now contains: -1 => value; -2 => key; -3 => table
        // copy the key so that lua_tostring does not modify the original
        lua_pushvalue(L,-2);
        // stack now contains: -1 => key; -2 => value; -3 => key; -4 => table
        const char *key = lua_tostring(L,-1);
        const char *value = lua_tostring(L,-2);
        printf(\"%s => %s\\n\",key,value);
        // pop value + copy of key,leaving original key
        lua_pop(L,2);
        // stack now contains: -1 => key; -2 => table
    }
    // stack now contains: -1 => table (when lua_next returns 0 it pops the key
    // but does not push anything.)
    // Pop table
    lua_pop(L,1);
    // Stack is now the same as it was on entry to this function
}
    ,从手册中:
const char *lua_tolstring (lua_State *L,int index,size_t *len);
  转换给定的Lua值   C字符串的可接受索引。如果len   不为NULL,它还将* len设置为   字符串长度。 Lua值必须   是字符串或数字;除此以外,   该函数返回NULL。如果   值是一个数字,然后是lua_tolstring   也会更改   堆叠成一个字符串。 (此更改   当lua_tolstring时混淆lua_next   在表期间应用于键   遍历。)
luaL_checkstring
lua_tolstring
。     ,另请参阅文档中“ѭ4”的示例,此处摘录如下:   
int lua_next (lua_State *L,int index);
     从堆栈中弹出一个键,并从表中按给定索引推送键-值对(给定键后的\“ next \”对)。如果表中没有其他元素,则
lua_next
返回0(并且不进行任何操作)。      典型的遍历如下所示:
/* table is in the stack at index \'t\' */
 lua_pushnil(L);  /* first key */
 while (lua_next(L,t) != 0) {
   /* uses \'key\' (at index -2) and \'value\' (at index -1) */
   printf(\"%s - %s\\n\",lua_typename(L,lua_type(L,-2)),-1)));
   /* removes \'value\'; keeps \'key\' for next iteration */
   lua_pop(L,1);
 }
     在遍历表时,请勿直接在键上调用
lua_tolstring
,除非您知道键实际上是字符串。回想一下“ 16”可能会更改给定索引处的值;这会使下一个呼叫
lua_next
感到困惑。      有关在遍历过程中修改表格的注意事项,请参见功能
next
。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-