How to create nested Lua tables using the C API

前端 未结 3 1627
北海茫月
北海茫月 2020-12-13 11:20

I want to create a table like

myTable = {
    [0] = { [\"a\"] = 4, [\"b\"] = 2 },
    [1] = { [\"a\"] = 13, [\"b\"] = 37 }
}

using the C AP

3条回答
  •  不思量自难忘°
    2020-12-13 12:06

    For simple code like the one you gave, my lua2c works fine and generates the code below.

    /* 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;
    }
    

提交回复
热议问题