c++ - 如何从 Lua 函数中获取多个返回表?

标签 c++ lua lua-table

我正在尝试将多个 float 组从 C++ 发送到 Lua 函数作为参数,然后从该函数返回多个表,以便我可以再次将它们用作 C++ 中的 float 组。

所以我的 Lua 函数看起来像这样。

function perform(arg1, arg2)
    local ret1, ret2 = {}, {}
    for i=1, #arg1 do
        ret1[i] = arg1[i] * 0.2;
        ret2[i] = arg2[i] * 0.3;
    end
    return ret1, ret2
end

这就是我在 C++ 中向/从 Lua 函数发送和返回多个表的方式。

lua_getglobal(L, "perform");

for (int i=0; i<numArgs; ++i) {

    lua_newtable(L);
    float *in = reinterpret_cast<float*>(w[i]);

    for (int j=0; j<64; ++j) {

        lua_pushinteger(L, j+1);
        lua_pushnumber(L, in[j]);
        lua_settable(L, -3);
    }
}
lua_call(L, numArgs, numRets);

for (int i=0; i<numRets; ++i) {

    float *out = reinterpret_cast<float*>(w[numArgs+i]);

    for (int j=0; j<64; ++j) {

        lua_pushinteger(L, j+1);
        lua_gettable(L, -2);
        out[j] = lua_tonumber(L, -1);
        lua_pop(L, 1);
    }
    //how to detect next returned table?
}

但如果我尝试代码,返回的数组具有相同的值。

我认为这是因为我没有正确获取返回的表。

谁能教我如何正确获取多个返回表?

P.S:我还想知道我的代码是否可以优化以获得更好的性能。

编辑:传递和返回一个包含多个子表的表会更快(更有效)吗?如果是这样,如果有人能教我怎么做,我将不胜感激。

最佳答案

我不知道你想在这里做什么,但是从函数返回的第二个表很容易在堆栈上访问。您只需对堆栈索引执行一些运算即可到达正确的位置。

那些 reinterpret_casts 在我看来非常可疑。你很可能做错了什么。

#include <iostream>
#include <vector>

#include <lua.hpp>

int main(int argc, char *argv[]) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <script.lua>\n";
        return 1;
    }

    luaL_dofile(L, argv[1]);

    // Mock data
    int numArgs = 2;
    int numRets = 2;
    std::vector<float> w1(64, 1.0f);
    std::vector<float> w2(64, 1.0f);
    std::vector<float> w3(64, 1.0f);
    std::vector<float> w4(64, 1.0f);
    std::vector<float *> w = {w1.data(), w2.data(), w3.data(), w4.data()};

    lua_getglobal(L, "perform");

    for (int i = 0; i < numArgs; ++i) {

        lua_newtable(L);
        float *in = reinterpret_cast<float *>(w[i]);

        for (int j = 0; j < 64; ++j) {
            lua_pushinteger(L, j + 1);
            lua_pushnumber(L, in[j]);
            lua_settable(L, -3);
        }
    }

    lua_call(L, numArgs, numRets);

    for (int i = 0; i < numRets; ++i) {

        float *out = reinterpret_cast<float *>(w[numArgs + i]);

        for (int j = 0; j < 64; ++j) {
            lua_pushinteger(L, j + 1);
            lua_gettable(L, -2 - i); // Just some stack index arithmetic
            out[j] = lua_tonumber(L, -1);
            lua_pop(L, 1);
        }
    }

    lua_close(L);
}

关于c++ - 如何从 Lua 函数中获取多个返回表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50854346/

相关文章:

indexing - 检查表中索引是否存在

c++ - 如何将 C++ vector 分配给非表全局变量

c++ - operator>> 执行期间出错:C++ 没有运算符匹配这些操作数 操作数类型为:std::istream >> const double error

c - Macosx、C 和嵌入式 lua

c++ - luabind:无法调用基本的 lua 函数,例如 print、tostring

LUA中的随机种子

Lua 表从 API 到主程序不可见

java - 如何使用简单的高斯分布算法将点分布在平面上?

c++ - 用于赋值的参数化构造函数

c++ - 为什么显示 ListView 图标时背景变黑?