c调用lua 出错异常处理

Qyee16 Qyee16 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
学习lua不久,遇到了问题,,请大家帮忙:
问题:访问了错误的lua函数程序崩溃的解决方法。


先上代码:

#include <stdio.h>
#include <assert.h>
#include <exception>

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
/*Lua解释器指针*/
lua_State* L;
int main ( int argc, char *argv[] )
{
L = luaL_newstate();
luaL_openlibs(L);
int iError = luaL_dofile(L, "test.lua");

lua_close(L);
int a = 11 ;
int b = 12 ;
(lua_getglobal(L,"add"));
if (lua_pcall(L, 0, 0, 0))
{
printf("Error calling lua function error");
}
lua_pushinteger(L,a) ;
lua_pushinteger(L,b) ;
int ret = lua_pcall(L,2,1,0) ;
if ( ret != 0 )
return 0;
printf("sum:%d + %d = %ld\n",a,b,lua_tointeger(L,-1)) ;
lua_pop(L,1);
/* 清除Lua */
lua_close(L);


getchar();

return 0;
}


lua脚本(为了测试问题,故意写错)
 --变量定义
width=1 ;
height=2 ;
--lua函数定义,实现加法
function sum(a,b)
return a+b ;
end


c++调用一个lua,试图去访问lua函数,lua中又没有此函数,(有时会出现此问题,访问了错误的lua文件,)

在此情况下,程序会崩溃,调试环境vs2012 、 lua52.dll 、 64位win7
(访问了错误的lua文件,怎么防止程序崩溃)
先谢谢大家了
...全文
评论 3
收藏 已收藏
分享
返回顶部
Qyee16
C++ 语言 65,214 成员 250,514 内容