简体   繁体   中英

How to read lua table in C

I have a table as follows:

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

}

I'm trying to read the table in lua using c. need to apply the values that will be made in function ARQSystem-> arqtable

But while reading the table I'm having error of: PANIC: unprotected error in call to Lua API (attempt to call a nil value)

My code is as follows:

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");

}

I wanted to know why it's happening this error in reading, am new to the lua I'm still learning, someone to help me?

Use lua_getglobal(L,"ARQtable") instead of lua_getfield(L,-1,"ARQtable") .

The error comes from trying to get a field from a table, when there is none on the stack at that moment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM