c - 使用 Lua C API 选择带有选择器字符串的嵌套值

标签 c lua lua-api

假设我在嵌套表中定义了一个值:tab["m"]["b"] = {}。 在 Lua 中,我可以用前面的语句定义它。

C API 也可以吗?具体来说,不是单独推送 tabm 等,而是使用单个字符串 tab["m"]["b"] 选择值>.

按下并选择它,就像使用单个值一样,(如下面的代码)不起作用。

lua_pushstring(state, "tab[\"m\"][\"b\"]");
lua_gettable(state, LUA_GLOBALSINDEX);

最佳答案

这在 C API 中是不可能的。如果你需要这个功能,你可以添加一个辅助函数来实现:

/* Pushes onto the stack the element t[k_1][...][k_n]
 * where t is the value at the given index and 
 * k_1, ..., k_n are the elements at the top of the stack
 * (k_1 being furthest from the top of the stack and
 *  k_n being at very the top of the stack).
 */
void recursive_gettable(lua_State *L, int index, int n) /*[-n,+1,e]*/ {
    luaL_checkstack(L, 2, NULL);           /*[k_1,...,k_n]*/
    lua_pushvalue(L, index);               /*[k_1,...,k_n,t]*/
    for (int i = 1; i <= n; ++i) {
        lua_pushvalue(L, -(n+1)+(i-1));    /*[k_1,...,k_n,t[...][k_(i-1)],k_i]*/
        lua_gettable(L, -2);               /*[k_1,...,k_n,t[...][k_i]]*/
    }
    lua_replace(L, -1, -(n+1));            /*[t[...][k_n],k_2,...,k_n]*/
    lua_pop(L, n-1);                       /*[t[...][k_n]] */
}

/*usage:*/
luaL_checkstack(L, 3, NULL);
lua_pushstring(L, "tab");
lua_pushstring(L, "m");
lua_pushstring(L, "b");
recursive_gettable(L, LUA_GLOBALSINDEX, 3);

关于c - 使用 Lua C API 选择带有选择器字符串的嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23849828/

相关文章:

go - 如何在不修改堆栈的情况下将表的内容转储到堆栈中?

c - 岩浆2.0错误: CUDA driver version is insufficient for CUDA runtime version

c - Windows API : Get micro seconds between milli seconds

string - 卢阿 : Incorrect string length for String with Special Characters

lua - Redis 服务器端脚本 - 一次 ZREM 多个值

c++ - 当元表 __index 指向函数且未使用返回值时 Lua 崩溃

c - lua中的 "dofile"和C API中的 "luaL_dofile"有什么区别?

c - 控制台图形如何工作? (less, curses, vi...)

c - "tc""th"C程序文件

string - 在Lua中分割字符串并打印选定的键