如何从 Lua 返回一个值列表给 C,然后逐个打印它们?
2015-10-2 16:56:9
收藏:0
阅读:105
评论:2
我正在使用与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有问题。有人可以帮我吗?
点赞
用户501459
你的代码有两个问题:
- 你在 Lua 代码的循环中使用了
return语句。一旦遇到return语句,Lua 脚本就完成执行。它将返回该值到 C 代码,这将是一个数字,而不是 C 代码期望的表。 - 你在没有先将一个起始键推入堆栈的情况下调用了
lua_next。
在你的 Lua 代码中,将以下内容更改为:
for i = 1,10 do
return(return_table [i])
end
更改为以下内容:
返回(return_table) - 顺便说一下,在此处不需要括号
在你的 C 代码中,在 while 循环之前添加 lua_pushnil(L)。
2015-10-02 16:33:02
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
当你执行
return语句时,Lua 脚本将停止。在脚本末尾的循环中,尝试使用如下代码:
return return_table