双11狂欢大促

盲盒赢 定制羽绒服

开启惊喜盲盒,抽取你的专属好礼

— 惊喜奖品抢先看 —

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

暴躁的野生猿 暴躁的野生猿 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
如果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值?
...全文
评论 1
收藏 已收藏
分享
返回顶部