将带有字段的表作为参数从C++传递给 Lua 函数?

Passing table with fields as an argument to Lua function from C++?

本文关键字:C++ Lua 函数 参数 字段      更新时间:2023-10-16

我想知道如何用字段和值形成一个Lua表,这样我就可以把它作为参数传递给C++的Lua函数。

我知道如何使用索引形成一个表格,但我不知道如何从由字段和值组成的表格中形成表格。

例如,我想将此表作为C++的参数发送到Lua函数。

t = {xpos = 50, ypos = 80, message = 'hello'}

下面的代码是我能得到的最接近的代码,但它只是没有字段名称的索引表。

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);

你也可以使用lua_setfield,这使得代码更短,可能更容易阅读:

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");

我不确定我是否正确理解了这个问题。 如果您希望字符串作为表中的键,则只需推送字符串而不是数字即可。

#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);
}