Home > other >  Error occurs attempt to index field in lua_getfield
Error occurs attempt to index field in lua_getfield

Time:11-24

I have a lua code where it is showing index error the error occurs when reading result

I'm using lua_gettop(L) for the index

My table is:

Avatar = 
{
    one = {
        vals = 51,
        result = 300,
    }
}

My code is:

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

    if (luaL_loadfile(L, "test.lua") || lua_pcall(L, 0, 0, 0))
    {
        printf("Error 'test.lua'\n");
        return;
    }

    lua_getglobal(L, "Avatar");

    lua_getfield(L, lua_gettop(L), "one");
    lua_getfield(L, lua_gettop(L), "vals");
    lua_getfield(L, lua_gettop(L), "result");


    lua_close(L);
    printf("Read complete.\n");

}

When reading the table, an error occurs

lua_getfield(L, lua_gettop(L), "result");

attempt to index field

What is the correct way for me to work this?

CodePudding user response:

    lua_getglobal(L, "Avatar");

    lua_getfield(L, lua_gettop(L), "one");
    lua_getfield(L, lua_gettop(L), "vals");
    lua_getfield(L, lua_gettop(L), "result");

Each of these lua_getfield calls pushes a new item onto the stack. First you push Avatar, then you index into that the one field, then the vals field, but the last line is effectively trying to read Avatar.one.vals.result, which does not exist.

You probably need to call lua_remove(L, -1) to pop the top of the stack (vals) before your last line that attempts to index result

  •  Tags:  
  • clua
  • Related