我有一个lua代码,它显示索引错误,错误发生时读取结果
我使用lua_gettop(L)
作为索引
我的表是:
Avatar =
{
one = {
vals = 51,
result = 300,
}
}
我的代码是:
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");
}
读取表时,出现错误
lua_getfield(L, lua_gettop(L), "result");
尝试索引字段
对我来说正确的工作方式是什么?
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_getfield
调用都将一个新项压入堆栈。首先推入Avatar
,然后索引到one
字段,然后索引到vals
字段,但是最后一行实际上试图读取不存在的Avatar.one.vals.result
。
您可能需要调用lua_remove(L, -1)
来弹出堆栈顶部(vals
),然后再尝试索引result