Reputation: 3044
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);
Upvotes: 2
Views: 1787
Reputation: 10939
I'm not sure whether I understand the question correctly. If you want strings as keys in the table, then just push strings instead of numbers.
#include <iostream>
#include <lua.hpp>
int main() {
lua_State *L = luaL_newstate();
luaL_openlibs(L);
char const script[] = "function test(t)\n"
" print(t.xpos)\n"
" print(t.ypos)\n"
" print(t.message)\n"
"end";
if (luaL_dostring(L, script) != 0) {
std::cerr << lua_tostring(L, -1) << '\n';
lua_close(L);
return 1;
}
lua_getglobal(L, "test");
if (lua_isfunction(L, -1)) {
lua_newtable(L);
// xpos = 50
lua_pushstring(L, "xpos");
lua_pushinteger(L, 50);
lua_settable(L, -3);
// ypos = 80
lua_pushstring(L, "ypos");
lua_pushinteger(L, 80);
lua_settable(L, -3);
// message = "hello"
lua_pushstring(L, "message");
lua_pushstring(L, "hello");
lua_settable(L, -3);
if (lua_pcall(L, 1, 0, 0) != 0) {
std::cerr << "lua:" << lua_tostring(L, -1) << '\n';
lua_close(L);
return 1;
}
}
lua_close(L);
}
Upvotes: 3
Reputation: 72312
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");
Upvotes: 4