How to add an empty table to an existing table in Lua using its C-API?

52 views Asked by At

The core detail of my problem is: I don't know how to do it.

I encountered the problem I'm trying to solve by wanting to add a table to an existing table in Lua.

The major difficulty that prevented me from solving it myself is ignorance, and a failure to come across any internet search results that are useful to me in solving the problem, despite my best efforts.

I tried the following, among other things:

  lua_getglobal(L, "OuterTable"); 
    lua_createtable(L, 0,0); 
    lua_pushliteral(L, "InnerTable");
    lua_settable(L,-2);

I expected that "InnerTable" would be added to "OuterTable" after considering the accepted answer of this question:

How to create table in table in Lua 5.1 using C-API?

Which also used lua_settable to add a table to a table, albeit a newly created one.

I have also looked through Programming In Lua, the color table example, but I was not able to solve it with that one, either.

Minimum reproducible example:

test.lua

OuterTable = {
    ExampleInnerTable = {}
}

Testbed in C (I use Lua 5.3 but my distro is set up in a peculiar way so ...I don't know how YOU would include it, be wary of that)

  #include <lua5.3/lua.h>
  #include <lua5.3/lualib.h>
  #include <lua5.3/lauxlib.h>

int main(int argc, char *argv[])
{
    


  lua_State* L;
  L = luaL_newstate();
  luaL_openlibs(L);
  luaL_dofile(L, "test.lua");

 lua_getglobal(L, "OuterTable"); 
 int c = lua_gettop(L);
 lua_newtable(L);
 lua_pushliteral(L, "InnerTable");
 lua_settable(L,c);

    return 0;
}

Basically, I want to add another table to OuterTable, one like ExampleInnerTable

Desired result

OuterTable = {
    ExampleInnerTable = {}
   ,InnerTable = {}
}
0

There are 0 answers