如何从 C 中访问嵌套的 Lua 表

假设我想在 Lua C API 中的嵌套表中设置一个值(例如一个函数)。

- lua.lua
glob = {
  nest = {
    - 在此处设置值
  }
}

我需要如何设置堆栈以访问inner表?

是否只需多次调用 gettable 然后调用 settop,就像以下代码中一样?

lua_pushstring(state, "glob");
lua_gettable(state, -1);
lua_pushstring(state, "nest");
lua_gettable(state, -1);

lua_pushcclosure(state, &func, 0);
lua_settop(state, "funkyfunc");

lua_pop(state, 2);
点赞
用户107090
用户107090

这段代码将glob.nest.name设置为一个 C 函数:

lua_getglobal(state, "glob");
lua_getfield(state, -1, "nest");
lua_pushcclosure(state, &func, 0);
lua_setfield(state, -1, "name");

如果要添加其他字段给glob.nest,只需要继续进行:

...
lua_pushcclosure(state, &anotherfunc, 0);
lua_setfield(state, -1, "anothername");
2014-04-28 23:56:38