c语言如何调用lua写的函数?
如果lua函数的形参和返回值都是整数,我现在已经可以用C语言调用它了。现在我想做的是,让lua函数返回字符串,用c语言读取lua的返回值,该怎么做呢?
先来看一下正确的例子:(lua函数的形参和返回值都是整数)
lua函数如下:
c语言函数如下:
以上代码没有问题,可以正确的按照我预期的样子运行。
下面再看看错误的代码,求教各路大神,问题出在哪?
贴代码:lua函数如下:
c语言调用lua函数的代码如下:
上述C语言代码,无法运行,直接报错,提示:unprotected errors in call to Lua API (attempt to call a nil value)
这个错误提示我理解不了,到底是在哪一行代码中,我引用了nil值?
先来看一下正确的例子:(lua函数的形参和返回值都是整数)
lua函数如下:
function add(x, y)
print("call lua_file add")
return x + y
endc语言函数如下:
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
endc语言调用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值?
...全文
相关推荐
C语言中调用Lua函数实例
主要介绍了C语言中调用Lua函数实例,本文讲解了调用一个Lua函数的步骤和C语言调用Lua函数实例,需要的朋友可以参考下
Lua中调用C语言函数实例
主要介绍了Lua中调用C语言函数实例,本文先讲解了相关知识,然后给出了调用实例,需要的朋友可以参考下
Lua编程示例(六): C语言调用Lua函数
主要介绍了Lua编程示例(六): C语言调用Lua函数,本文直接给出代码实例,需要的朋友可以参考下
lua和c语言之间相互调用实例
lua和c语言之间相互调用实例
Lua教程(二十):Lua调用C函数
主要介绍了Lua教程(二十):Lua调用C函数,本文讲解了C函数作为应用程序的一部分、C函数库成为Lua的模块等内容,需要的朋友可以参考下


工具平台和程序库

