3

我正在使用嵌入 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 的传递有问题。谁能帮我解决这个问题?

4

2 回答 2

2

您的代码有两个问题:

  1. 您的 Lua 代码的循环中有一个return语句。一旦返回语句被命中,你的 Lua 脚本就完成了执行。它将那个值返回给 C 代码,它将是一个数字,而不是您的 C 代码所期望的表。
  2. lua_next无需先将启动键压入堆栈即可调用。

在你的 Lua 代码中,改变这个:

for i=1,10 do 
    return(return_table[i])
end

对此:

return(return_table) -- don't need parentheses here, btw

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

于 2015-10-02T16:33:02.497 回答
1

一旦你执行return,Lua 脚本就会停止。

而不是脚本末尾的循环,简单地尝试

return return_table
于 2015-10-02T16:21:49.143 回答