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

Zac*_*Lee 4 c c++ lua

我想知道如何从Lua C API中的函数获取多个返回值。

Lua代码:

function test(a, b)
  return a, b -- I would like to get these values in C++
end
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

我得到的结果是:

返回:4 4

我期望的结果:

返回:3 4

YSC*_*YSC 5

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);
Run Code Online (Sandbox Code Playgroud)

在调用之前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
+===========+
Run Code Online (Sandbox Code Playgroud)

通话2之后

lua_pcall(L, 2, 2, 0) 

+-----------+
|     3     |  <--- -1
+-----------+
|     4     |  <--- -2
+===========+
Run Code Online (Sandbox Code Playgroud)

另一种方法是在阅读结果后手动弹出结果:

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);
Run Code Online (Sandbox Code Playgroud)

1)如果一个函数返回多个结果,则第一个结果首先被压入;因此,如果有n结果,则第一个将在index处-n,最后一个在index处-1。” 在Lua中编程:25.2

2)在推送结果之前,lua_pcall从堆栈中删除函数及其参数。” 在Lua中编程:25.2