Here's a full and minimal program demonstrating how to nest tables. Basically what you are missing is the lua_setfield
function.
#include <stdio.h>
#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
", lua_tostring(L, -1));
}
return 0;
}
The program will simply print true
.
If you need numeric indices, then you continue using lua_settable
:
#include <stdio.h>
#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
", lua_tostring(L, -1));
}
return 0;
}
Rather than using absolute indices of 0 like I did, you might want to use lua_objlen
to generate the index.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…