如何在C中读取Lua表格

我有一个表格如下:

ARQtable =
{
    120,  250,  400,  500,  730,
    790,  810,  935,  950,  999,

}

我正在尝试使用 c 读取 lua 中的表格。需要在函数 ARQSystem-> arqtable 中使用生成的值。

但是,在读取表时,我遇到以下错误:PANIC: unprotected error in call to Lua API (attempt to call a nil value)

我的代码如下:

void read_table(void){
    lua_State *L;
    L = luaL_newstate();
    luaL_openlibs(L);

    int val = 2000, i = 0;
    if (luaL_loadfile(L, "tables.lua") || lua_pcall(L, 0, 0, 0))
    {
        ShowError("Error reading 'tables.lua'\n");
        return;
    }

    lua_getglobal(L, "ARQtable");
    if (lua_type(L, -1) == LUA_TTABLE) {
        for (i = 0; i < val; i++) {
            lua_pushnumber(L, i);
            lua_gettable(L, -2);
            ARQSystem->arqtable[i] = lua_isnumber(L, -1);
            lua_settop(L, -2);
        }
    }
    lua_close(L);
    printf("Read Table complete.\n");
}

我想知道为什么在读取时出现这个错误,我是 lua 新手,仍在学习,能有人帮助我吗?

点赞
用户107090
用户107090

使用lua_getglobal(L,"ARQtable")而不是lua_getfield(L,-1,"ARQtable")

当堆栈中没有表字段时,尝试从表中获取字段会导致错误。

2015-10-10 21:54:32