我试图将多个浮点数组从C ++发送到Lua函数作为参数,然后从该函数返回多个表,以便可以再次将它们用作C ++中的浮点数组。
因此我的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?
}
但是,如果我尝试代码,则返回的数组具有相同的值。
我认为这是因为我没有正确获取返回的表。
有人可以教我如何正确获取多个返回表吗?
PS:我也想知道我的代码是否可以优化以获得更好的性能。
编辑:通过并返回具有多个子表的一个表会更快(更有效率)吗?如果是这样,我将不胜感激,如果有人能教我该怎么做。
我不知道您要在这里做什么,但是从函数返回的第二张表很容易在堆栈上访问。您只需要对堆栈索引执行一些算术即可到达正确位置。
那些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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句