通过Lua的表迭代 [英] Iterate through Lua Table

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

问题描述

我想通过一个Lua表进行迭代,但我不断收到此错误:

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

invalid key to 'next'

我知道,指数-8开始了,我知道有一个表存在,因为它在它获得的第一个(也是唯一)值。但是,它会循环轮再次尽管我知道只有一个表中的字符串。

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

任何帮助将是AP preciated。

Any help would be appreciated.

此,当我用一个积极的指标(只要我不从中取出1)正常工作

编辑:我注意到我,如果我独自离开物品的价值没有得到这个错误。只有当我开始阅读项目的价值做我得到这个错误。当我有从表中的值,我调用另一个Lua的功能,这会是干扰lua_next?

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?

推荐答案

不要使用 luaL_checkstring 负参数。使用 lua_tostring 代替。

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

此外,还要确保你调用的循环功能后堆栈是相同的: lua_next 预计在堆栈的顶部previous表键,以便它可以继续穿越。

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天全站免登陆