c语言如何调用lua写的函数?

暴躁的野生猿 2018-07-31 08:52:44
如果lua函数的形参和返回值都是整数,我现在已经可以用C语言调用它了。现在我想做的是,让lua函数返回字符串,用c语言读取lua的返回值,该怎么做呢?
先来看一下正确的例子:(lua函数的形参和返回值都是整数)
lua函数如下:
function add(x, y)
print("call lua_file add")
return x + y
end

c语言函数如下:
int lua_add(int x,int y)
{
int sum;
/*the function name*/
lua_getglobal(L,"add");
/*the first argument*/
lua_pushnumber(L,x);
/*the second argument*/
lua_pushnumber(L,y);
/*call the function with 2 arguments, return 1 result.*/
lua_call(L,2,1);
/*get the result.*/
sum = (int)lua_tonumber(L,-1);//可以正确读出返回值
/*cleanup the return*/
lua_pop(L,1);
return sum;
}

以上代码没有问题,可以正确的按照我预期的样子运行。

下面再看看错误的代码,求教各路大神,问题出在哪?
贴代码:lua函数如下:
function parse(did)
string str = "did is not 1"
print("call lua_file parse")
if(1 == did)
then
str = "did is 1"
end
return str
end


c语言调用lua函数的代码如下:
int lua_parse(int did)
{
const char *buf;
uint len;
/*the function name*/
lua_getglobal(L,"parse");
/*the first argument*/
lua_pushnumber(L,did);
/*call the function with 1 arguments, return 1 result.*/
lua_call(L,1,1);
/*get the result.*/
buf = lua_tolstring(L,-1, &len);//我以为buf会得到lua函数返回的字符串的首地址
printf("ret len = %d\r\n", len);
/*cleanup the return*/
lua_pop(L,1);
return 0;
}

上述C语言代码,无法运行,直接报错,提示:unprotected errors in call to Lua API (attempt to call a nil value)
这个错误提示我理解不了,到底是在哪一行代码中,我引用了nil值?
...全文
213 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
donjin9 2018-08-01
  • 打赏
  • 举报
回复
lua函数中,string类型好像要删掉吧。print需要加luaopen_base(L)或者luaL_openlibs(L)。

24,854

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧