5

How to create Lua table from C-API like this:

TableName = {a, b, c}

How to set table name? I only know how to create table and put values, but don't know how to set name of table.

Code for creating table without name:

lua_createtable(L, 0, 3);

lua_pushnumber(L, 1);
lua_setfield(L, -2, "a");

lua_pushnumber(L, 2);
lua_setfield(L, -2, "b");

lua_pushnumber(L, 3);
lua_setfield(L, -2, "c");
hjpotter92
  • 78,589
  • 36
  • 144
  • 183
BORSHEVIK
  • 794
  • 1
  • 8
  • 12
  • 1
    For the sake for clarity, you are asking about a variable having the name TableName. A table, like any Lua value, does not have a name. – Tom Blodget Jun 16 '16 at 21:52

1 Answers1

4

All you need is to add this line at the end

lua_setglobal(L, "TableName");

However, your C code is not equivalent to your Lua code. The C code corresponds to this Lua code:

TableName = { a=1, b=2, c=3 }

If you want C code equivalent to

TableName = {"a", "b", "c"}

use

lua_pushliteral(L, "a"); lua_rawseti(L, -2, 1);
lua_pushliteral(L, "b"); lua_rawseti(L, -2, 2);
lua_pushliteral(L, "c"); lua_rawseti(L, -2, 3);
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thanks. And how I can set the table in the table in the table? Like this a = {["b"] = {["c"] = {["d"] = {["e"] = "GOOD"}}}} ? print(a.b.c.d.e); – BORSHEVIK Jun 16 '16 at 18:24
  • http://stackoverflow.com/questions/37854422/how-to-create-table-in-table-in-lua-5-1-using-c-api – BORSHEVIK Jun 16 '16 at 20:03