Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Lua table with name C-API

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");
like image 601
BORSHEVIK Avatar asked Jun 16 '16 13:06

BORSHEVIK


1 Answers

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);
like image 52
lhf Avatar answered Nov 15 '22 03:11

lhf