从C++向Lua函数传递带有字段的表格作为参数的方法?

我想知道如何组成一个 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);

点赞
用户1944004
用户1944004

我不确定是否正确理解了问题。如果您想在表中使用字符串作为键,则只需推送字符串而不是数字。

#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);
}
2018-07-07 06:48:39
用户107090
用户107090

你也可以使用 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");
2018-07-07 17:17:21