我想知道如何从 Lua C API 中的函数获取多个返回值。
Lua代码:
function test(a, b)
return a, b -- I would like to get these values in C++
end
C++ 代码:(调用函数的部分)
/* push functions and arguments */
lua_getglobal(L, "test"); /* function to be called */
lua_pushnumber(L, 3); /* push 1st argument */
lua_pushnumber(L, 4); /* push 2nd argument */
/* call the function in Lua (2 arguments, 2 return) */
if (lua_pcall(L, 2, 2, 0) != 0)
{
printf(L, "error: %s\n", lua_tostring(L, -1));
return;
}
int ret1 = lua_tonumber(L, -1);
int ret2 = lua_tonumber(L, -1);
printf(L, "returned: %d %d\n", ret1, ret2);
我得到的结果:
returned: 4 4
我期望的结果:
returned: 3 4
最佳答案
lua_tonumber
不会改变 lua_State
的堆栈。您需要在两个不同的索引处阅读它1:
int ret1 = lua_tonumber(L, -2);
int ret2 = lua_tonumber(L, -1);
printf(L, "returned: %d %d\n", ret1, ret2);
在调用 test
之前,您的堆栈如下所示:
lua_getglobal(L, "test"); /* function to be called */
lua_pushnumber(L, 3); /* push 1st argument */
lua_pushnumber(L, 4); /* push 2nd argument */
| 4 | <--- 2
+-----------+
| 3 | <--- 1
+-----------+
| test | <--- 0
+===========+
调用2后:
lua_pcall(L, 2, 2, 0)
+-----------+
| 3 | <--- -1
+-----------+
| 4 | <--- -2
+===========+
另一种方法是在您阅读结果后手动弹出结果:
int ret1 = lua_tonumber(L, -1);
lua_pop(L, 1);
int ret2 = lua_tonumber(L, -1);
lua_pop(L, 1);
printf(L, "returned: %d %d\n", ret1, ret2);
1) "如果一个函数返回多个结果,第一个结果首先被压入;因此,如果有 n
个结果,第一个将被压入在索引 -n
,最后一个在索引 -1
。” Programming in Lua : 25.2
2) “在推送结果之前,lua_pcall
从堆栈中移除函数及其参数。” Programming in Lua : 25.2
关于c++ - 如何从 Lua C API 中的函数获取多个返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786044/