![](/img/trans.png)
[英]How to bind a C++ function to lua that return multiple values with luabind?
[英]How to get multiple return values from function in Lua C API?
我想知道如何从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);
结果我得到:
返回:4 4
结果我期待:
返回: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
。” Lua编程:25.2
2) “ 在推送结果之前, lua_pcall
从lua_pcall
删除函数及其参数 。” Lua编程:25.2
您使用相同的索引两次:
int ret1 = lua_tonumber(L, -1);
int ret2 = lua_tonumber(L, -1);
堆栈填充如下:
-- Lua
return a, b
+---+
| b | <-- top ("relative" index -1)
+---+
| a | <-- -2
+---+
所以你的C ++代码应该是:
// I don't know what ret1 or ret2 suppose to be.
// 1 = first on stack, or first return value?
// renamed to a and b for consistency with lua return a,b
int b = lua_tonumber(L, -1);
int a = lua_tonumber(L, -2);
// lua_pop(L, 2); // don't forget to pop the values
[...] lua_gettop函数返回堆栈中元素的数量,这也是顶部元素的索引。 请注意,负索引-x等于正索引gettop - x + 1. [...]
这个负的indeces定位对于有关堆栈访问的所有Lua函数都有效,包括lua_tonumber。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.