遍历 Lua 表 [英] Iterate through Lua Table

查看:28
本文介绍了遍历 Lua 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历 lua 表,但我不断收到此错误:

'next' 的无效键

我知道索引从 -8 开始,并且我知道那里有一个表,因为它获得了其中的第一个(也是唯一一个)值.但是,即使我知道表中只有一个字符串,它也会尝试再次循环.

if (lua_istable(L, index)){lua_pushnil(L);//这是它获得第一个值所必需的指数 - ;而(lua_next(L,索引)!= 0){const char *item = luaL_checkstring(L, -1);lua_pop(L, 1);printf("%s
", item);}}别的{luaL_typerror(L, index, "字符串表");}

任何帮助将不胜感激.

这在我使用正索引时效果很好(只要我不从中删除 1)

我注意到如果我单独保留 item 的值,我不会收到此错误.只有当我开始读取 item 的值时,才会出现此错误.当我从表中得到值后,我调用另一个 Lua 函数,这会不会干扰 lua_next?

解决方案

不要使用带有否定参数的 luaL_checkstring.改用 lua_tostring.

此外,确保在循环中调用函数后堆栈保持不变:lua_next 期望前一个表键位于堆栈顶部,以便它可以继续遍历.>

I am trying to iterate through a lua table but I keep getting this error:

invalid key to 'next'

I know that index starts off as -8 and I know that there is a table there because it gets the first (and only) value in it. However, it tries to loop round again even though I know there is only one string in the table.

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
", item);
    }
}
else
{
    luaL_typerror(L, index, "string table");
}

Any help would be appreciated.

This works fine when I use a positive index (as long as I don't remove 1 from it)

Edit: I've noticed that I don't get this error if I leave the value of item alone. Only when I start reading the value of item do I get this error. When I've got the value from the table, I call another Lua function, could this be disrupting lua_next?

解决方案

Do not use luaL_checkstring with negative arguments. Use lua_tostring instead.

Also, make sure the stack remains the same after you call a function in the loop: lua_next expects the previous table key at the top of the stack so that it can resume the traversal.

这篇关于遍历 Lua 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆