【问题标题】:How to access nested Lua tables from C如何从 C 访问嵌套的 Lua 表
【发布时间】:2014-04-28 21:02:30
【问题描述】:

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

-- lua.lua
glob = { 
  nest = { 
    -- set value in here
  }
}

我必须如何设置堆栈才能访问内表?

是否只是多次调用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);

【问题讨论】:

  • 你需要lua_getglobal,然后是lua_gettable
  • 你打算用lua_settop(state, "funkyfunc")做什么?

标签: c lua lua-table


【解决方案1】:

此代码将 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");

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 2018-04-12
    • 2023-03-09
    • 2021-10-09
    • 2016-04-11
    • 1970-01-01
    • 2012-07-13
    • 2014-08-28
    相关资源
    最近更新 更多