我想创建一个像这样的表
myTable = { [0] = { ["a"] = 4, ["b"] = 2 }, [1] = { ["a"] = 13, ["b"] = 37 } }
使用C API?
我目前的做法是
lua_createtable(L, 0, 2); int c = lua_gettop(L); lua_pushstring(L, "a"); lua_pushnumber(L, 4); lua_settable(L, c); lua_pushstring(L, "b"); lua_pushnumber(L, 2); lua_settable(L, c);
在循环中创建内部表.之前,这个循环,我用
lua_createtable(L, 2, 0); int outertable = lua_gettop(L);
为2个数字槽创建外部表.
但是如何将内部表保存到外部表?
这是一个完整的,最小的程序,演示如何嵌套表.基本上你缺少的是lua_setfield
功能.
#include#include "lua.h" #include "lauxlib.h" #include "lualib.h" int main() { int res; lua_State *L = lua_open(); luaL_openlibs(L); lua_newtable(L); /* bottom table */ lua_newtable(L); /* upper table */ lua_pushinteger(L, 4); lua_setfield(L, -2, "four"); /* T[four] = 4 */ lua_setfield(L, -2, "T"); /* name upper table field T of bottom table */ lua_setglobal(L, "t"); /* set bottom table as global variable t */ res = luaL_dostring(L, "print(t.T.four == 4)"); if(res) { printf("Error: %s\n", lua_tostring(L, -1)); } return 0; }
该程序将简单打印true
.
如果您需要数字索引,那么您继续使用lua_settable
:
#include#include "lua.h" #include "lauxlib.h" #include "lualib.h" int main() { int res; lua_State *L = lua_open(); luaL_openlibs(L); lua_newtable(L); /* bottom table */ lua_newtable(L); /* upper table */ lua_pushinteger(L, 0); lua_pushinteger(L, 4); lua_settable(L, -3); /* uppertable[0] = 4; pops 0 and 4 */ lua_pushinteger(L, 0); lua_insert(L, -2); /* swap uppertable and 0 */ lua_settable(L, -3); /* bottomtable[0] = uppertable */ lua_setglobal(L, "t"); /* set bottom table as global variable t */ res = luaL_dostring(L, "print(t[0][0] == 4)"); if(res) { printf("Error: %s\n", lua_tostring(L, -1)); } return 0; }
您可能希望使用lua_objlen
生成索引,而不是像我一样使用0的绝对索引.
对于像你给出的简单代码,我的lua2c工作正常并生成下面的代码.
/* This C code was generated by lua2c from the Lua code below. myTable = { [0] = { ["a"] = 4, ["b"] = 2 }, [1] = { ["a"] = 13, ["b"] = 37 } } */ static int MAIN(lua_State *L) { lua_newtable(L); lua_pushnumber(L,0); lua_newtable(L); lua_pushliteral(L,"a"); lua_pushnumber(L,4); lua_pushliteral(L,"b"); lua_pushnumber(L,2); lua_settable(L,-5); lua_settable(L,-3); lua_pushnumber(L,1); lua_newtable(L); lua_pushliteral(L,"a"); lua_pushnumber(L,13); lua_pushliteral(L,"b"); lua_pushnumber(L,37); lua_settable(L,-5); lua_settable(L,-3); lua_settable(L,-5); lua_settable(L,-3); lua_setglobal(L,"myTable"); return 0; }