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