繁体   English   中英

如何从Lua C API函数中获取多个返回值?

[英]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_pcalllua_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

24.2.3开始 - 其他堆栈操作

[...] lua_gettop函数返回堆栈中元素的数量,这也是顶部元素的索引。 请注意,负索引-x等于正索引gettop - x + 1. [...]

这个负的indeces定位对于有关堆栈访问的所有Lua函数都有效,包括lua_tonumber。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM