TA的每日心情 | 郁闷 2019-9-30 18:03 |
---|
签到天数: 33 天 [LV.5]常住居民I
VIP会员
  
- 积分
- 7576
|
本帖最后由 1149 于 2018-10-8 13:54 编辑
1,调用LUA函数
[mw_shl_code=cpp,true]int main(void)
{
lua_State *L = lua_open();
luaopen_base(L);//加载基础库
luaopen_string(L);//加载字符串库
luaopen_table(L);//加载表处理库
lua_register(L, "test", test);
if (luaL_loadfile(L, "main.lua"))
{
printf("加载错误:%s\n", lua_tostring(L, -1));
}
if (lua_pcall(L, 0, 0, 0))
{
printf("调用错误:%s\n", lua_tostring(L, -1));
}
lua_getglobal(L, "pr");//获得全局函数pr并压入栈
if (lua_pcall(L, 0, 0, 0))//调用栈顶的pr函数
{
printf("调用错误:%s\n", lua_tostring(L, -1));
}
getchar();
return 0;
}[/mw_shl_code]
2,给LUA函数传递参数,并获取LUA函数的返回值
[mw_shl_code=cpp,true]int main(void)
{
lua_State *L = lua_open();
luaopen_base(L);//加载基础库
luaopen_string(L);//加载字符串库
luaopen_table(L);//加载表处理库
lua_register(L, "test", test);
printf("堆栈个数为:%d\n", lua_gettop(L));//查看顶层堆栈索引
if (luaL_loadfile(L, "main.lua"))
{
printf("加载错误:%s\n", lua_tostring(L, -1));
}
if (lua_pcall(L, 0, 0, 0))
{
printf("调用错误:%s\n", lua_tostring(L, -1));
}
lua_getglobal(L, "pr");//获得全局函数pr并压入栈
lua_pushstring(L , "我是第一个参数");
lua_pushstring(L , "我是第二个参数");
if (lua_pcall(L, 2, 1, 0))//调用栈顶的pr函数,2代表接受2个参数,1代表接受一个返回值
{
printf("调用错误:%s\n", lua_tostring(L, -1));
}
else
{
printf("fr的返回值:%s\n" , lua_tostring(L , -1));
lua_pop(L, 1);//把返回值pop出堆栈,恢复初始堆栈
}
printf("堆栈个数为:%d\n", lua_gettop(L));//查看顶层堆栈索引
getchar();
return 0;
}[/mw_shl_code]
3,调用lua_pcall错误处理函数
[mw_shl_code=cpp,true]int main(void)
{
lua_State *L = lua_open();
luaopen_base(L);//加载基础库
luaopen_string(L);//加载字符串库
luaopen_table(L);//加载表处理库
lua_register(L, "test", test);
printf("堆栈个数为:%d\n", lua_gettop(L));//查看等层堆栈索引
if (luaL_loadfile(L, "main.lua"))
{
printf("加载错误:%s\n", lua_tostring(L, -1));
}
if (lua_pcall(L, 0, 0, 0))
{
printf("调用错误:%s\n", lua_tostring(L, -1));
}
lua_getglobal(L, "err");//压入错误处理函数
int id = lua_gettop(L);//记录错误处理函数索引
lua_getglobal(L, "pr");//获得全局函数pr并压入栈
lua_pushstring(L , "我是第一个参数");
if (lua_pcall(L, 1, 0, id))//调用栈顶的pr函数,1代表接受1个参数,id代表错误处理函数在栈中的索引,当运行完毕后函数自身和参数会自动出栈
{
printf("调用错误:%s\n", lua_tostring(L, -1));//如果指定了错误处理函数,错误处理函数的返回值将被 lua_pcall 作为错误消息返回在堆栈上
//否则栈顶的错误消息就和原始错误消息完全一致
lua_pop(L, 1);
}
else
{
//printf("fr的返回值:%s\n" , lua_tostring(L , -1));
//lua_pop(L, 1);//把返回值pop出堆栈,恢复初始堆栈
}
lua_pop(L, 1);//把错误处理函数出栈
printf("堆栈个数为:%d\n", lua_gettop(L));//查看等层堆栈索引
getchar();
return 0;
}[/mw_shl_code]
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|