I would like to know how to form a Lua table with fields and values so I can pass it as an argument to a Lua function from C++.
I know how to form a table using indices but I don't know how to from a table made of fields and values.
For example, I want to send this table to a Lua function as an argument from C++.
t = {xpos = 50, ypos = 80, message = 'hello'}
The below code is the closest I could get, but it's just indexed table with no field name.
lua_getglobal(L, "myLuaFunc");
if (lua_type(L, -1) == LUA_TFUNCTION)
{
lua_newtable(L);
lua_pushinteger(L, 1);
lua_pushnumber(L, 50);
lua_pushinteger(L, 2);
lua_pushnumber(L, 80);
lua_pushinteger(L, 3);
lua_pushstring(L, 'hello');
lua_settable(L, -3);
if (lua_pcall(L, 1, 0, 0))
std::cout << "Error : " << lua_tostring(L, -1) << std::endl;
}
lua_pop(L, 1);
You can also use lua_setfield
, which makes the code shorter and probably easier to read:
lua_newtable(L);
lua_pushinteger(L, 50); // xpos = 50
lua_setfield(L, -2, "xpos");
lua_pushinteger(L, 80); // ypos = 80
lua_setfield(L, -2, "ypos");
lua_pushstring(L, "hello"); // message = "hello"
lua_setfield(L, -2, "message");