1

Hi I want lua C api to create Lua table like

table={['key1']={5,4,3,2},['key2']={1,0,1,1,0},['key3']={0,10,0,30,0,50}}

thanks in-advance....

Abhi
  • 73
  • 8

1 Answers1

3

My lua2c gives this:

lua_newtable(L);
lua_pushliteral(L,"key1");
lua_newtable(L);
lua_pushnumber(L,5);
lua_pushnumber(L,4);
lua_pushnumber(L,3);
lua_pushnumber(L,2);
lua_rawseti(L,-5,4);
lua_rawseti(L,-4,3);
lua_rawseti(L,-3,2);
lua_rawseti(L,-2,1);
lua_pushliteral(L,"key2");
lua_newtable(L);
lua_pushnumber(L,1);
lua_pushnumber(L,0);
lua_pushnumber(L,1);
lua_pushnumber(L,1);
lua_pushnumber(L,0);
lua_rawseti(L,-6,5);
lua_rawseti(L,-5,4);
lua_rawseti(L,-4,3);
lua_rawseti(L,-3,2);
lua_rawseti(L,-2,1);
lua_pushliteral(L,"key3");
lua_newtable(L);
lua_pushnumber(L,0);
lua_pushnumber(L,10);
lua_pushnumber(L,0);
lua_pushnumber(L,30);
lua_pushnumber(L,0);
lua_pushnumber(L,50);
lua_rawseti(L,-7,6);
lua_rawseti(L,-6,5);
lua_rawseti(L,-5,4);
lua_rawseti(L,-4,3);
lua_rawseti(L,-3,2);
lua_rawseti(L,-2,1);
lua_settable(L,-7);
lua_settable(L,-5);
lua_settable(L,-3);
lua_setglobal(L,"table");

This automatically generated code postpones setting table entries to the end; it can be more readable to set them as soon as possible, but you need to adjust the indices carefully.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    For a recent thread on this, see http://lua-users.org/lists/lua-l/2022-01/msg00156.html – lhf Feb 01 '22 at 14:22