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

1

を実行するreturnと、Lua スクリプトが停止します。

スクリプトの最後のループの代わりに、単純に試してください

return return_table
于 2015-10-02T16:21:49.143 に答える