【问题标题】:Passing table with fields as an argument to Lua function from C++?将带有字段的表作为参数从 C++ 传递给 Lua 函数?
【发布时间】:2018-12-15 15:37:03
【问题描述】:

我想知道如何用字段和值形成一个 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);

【问题讨论】:

  • 所以我们可以假设(从示例中),您已经找到 this?
  • @πάνταῥεῖ 我刚刚做了。但我不认为它有帮助。
  • 我不是 100% 确定如何将表的 字段名称 传递给 lua,但我猜你可以使用其他一些接口函数。

标签: c++ lua lua-table


【解决方案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");

【讨论】:

    【解决方案2】:

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

    #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-12-16
    • 1970-01-01
    • 2016-11-06
    • 2021-10-10
    • 2013-08-30
    • 2013-07-13
    • 2020-04-01
    • 1970-01-01
    相关资源
    最近更新 更多