如何从 Lua 返回一个值列表给 C,然后逐个打印它们?

我正在使用与Lua嵌入的C API。我的目标是:将整数数组传递到Lua中并计算它们的阶乘,然后将结果传回C并打印出来。

为了实现这个目标,我的C代码是:

#include <lua.h>
#include <lauxlib.h>
#include <stdlib.h>
#include <stdio.h>

int main(void){
  int status, result, i;
  double fac;

  lua_State *L;  // set Lua state
  L = luaL_newstate();

  luaL_openlibs(L);

  status = luaL_loadfile(L, "factorial.lua");  // load the Lua script for factorial calculation
  if (status) {
    fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
    exit(1);
  }

  lua_newtable(L);

  for (i = 1; i <= 10; i++) {
    lua_pushnumber(L, i);   /* Push the table index */
    lua_pushnumber(L, i*2); /* Push the cell value */
    lua_rawset(L, -3);      /* Stores the pair in the table */
  }

  lua_setglobal(L, "foo");

  result = lua_pcall(L, 0, LUA_MULTRET, 0);
  if (result) {
    fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
    exit(1);
  }

  // the following loop is for factorial print-out
  while (lua_next(L, -1) != 0) {
    fac = lua_tonumber(L, -1);
    printf("%.0f\n", fac);
    lua_pop(L, 1);
  }

  lua_close(L);

  return 0;
}

我的Lua脚本如下:

-- this is the function to calculate the factorial
function fact(n)
if n == 0 then
       return 1
else
   return n * fact(n-1)
end
end

io.write("We calculate the factorial of the following numbers: \n")

return_table = {}
for i = 1, #foo do
 n = foo[i]
 factorial_result = fact(n)
 print(n)
 table.insert(return_table, factorial_result)
end

io.write("Here we show the results: \n")
for i=1,10 do
return(return_table[i])
end

编译很顺利,但当我在终端上运行它时,我得到了:

We calculate the factorial of the following numbers:
2.0
4.0
6.0
8.0
10.0
12.0
14.0
16.0
18.0
20.0
Here we show the results:
Segmentation fault (core dumped)

我不知道为什么结果是这样的。似乎从C传递到Lua没有问题,但从Lua到C有问题。有人可以帮我吗?

点赞
用户107090
用户107090

当你执行 return 语句时,Lua 脚本将停止。

在脚本末尾的循环中,尝试使用如下代码:

return return_table
2015-10-02 16:21:49
用户501459
用户501459

你的代码有两个问题:

  1. 你在 Lua 代码的循环中使用了 return 语句。一旦遇到 return 语句,Lua 脚本就完成执行。它将返回该值到 C 代码,这将是一个数字,而不是 C 代码期望的表。
  2. 你在没有先将一个起始键推入堆栈的情况下调用了 lua_next

在你的 Lua 代码中,将以下内容更改为:

for i = 110 do
    return(return_table [i])
end

更改为以下内容:

返回(return_table) - 顺便说一下,在此处不需要括号

在你的 C 代码中,在 while 循环之前添加 lua_pushnil(L)

2015-10-02 16:33:02