C 使用luaapi选择带有选择器字符串的嵌套值
假设我在嵌套表中定义了一个值:C 使用luaapi选择带有选择器字符串的嵌套值,c,lua,lua-api,C,Lua,Lua Api,假设我在嵌套表中定义了一个值:tab[“m”][“b”]={}。 在Lua中,我可以用前面的语句定义它 C API也可以吗?具体来说,不要单独按下选项卡、m等,而是使用单个字符串选项卡[“m”][“b”]选择值 按下并选择它,就像使用单个值一样(如下面的代码中所示),不起作用 lua_pushstring(state, "tab[\"m\"][\"b\"]"); lua_gettable(state, LUA_GLOBALSINDEX); 这在C API中是不可能的。如果需要此功能,可以添加一
tab[“m”][“b”]={}
。
在Lua中,我可以用前面的语句定义它
C API也可以吗?具体来说,不要单独按下选项卡
、m
等,而是使用单个字符串选项卡[“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);
/*将元素t[k_1][…][k_n]推到堆栈上
*其中t是给定索引处的值,且
*k_1,…,k_n是堆栈顶部的元素
*(k_1距离烟囱顶部最远,且
*k_n处于最顶端)。
*/
void recursive_gettable(lua_State*L,int index,int n)/*[-n,+1,e]*/{
luaL_校验堆栈(L,2,NULL);/*[k_1,…,k_n]*/
lua_pushvalue(L,index);/*[k_1,…,k_n,t]*/
对于(int i=1;i