【问题标题】:How to return a list of values from Lua to C and print them one by one?如何将 Lua 中的值列表返回到 C 并一一打印?
【发布时间】:2023-03-31 18:58:02
【问题描述】:

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

【问题讨论】:

    标签: c lua lua-api


    【解决方案1】:

    你的代码有两个问题:

    1. 在 Lua 代码的循环内有一个 return 语句。一旦返回语句被命中,你的 Lua 脚本就完成了执行。它会将该值返回给 C 代码,它将是一个数字,而不是您的 C 代码所期望的表。
    2. 你打电话给lua_next 没有先pushing a starting key onto the stack

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

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

    到这里:

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

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

    【讨论】:

    • 您好,非常感谢您的回答。但是,我仍然有“分段错误”的问题如下:我们计算以下数字的阶乘:2.0 4.0 6.0 8.0 10.0 12.0 14.0 16.0 18.0 20.0 这里我们显示结果:0 分段错误(核心转储)
    • 哦,我明白了,可能是因为我没有做 lua_getglobal
    【解决方案2】:

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

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

    return return_table
    

    【讨论】:

      猜你喜欢
      • 2023-01-01
      • 2017-11-17
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2019-11-29
      • 2022-07-04
      • 2011-09-04
      • 2021-04-05
      相关资源
      最近更新 更多