c调用lua 出错异常处理

Qyee16 2014-09-29 12:29:56
学习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文件,怎么防止程序崩溃)
先谢谢大家了
...全文
581 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Qyee16 2014-09-29
  • 打赏
  • 举报
回复
修改后代码,,用 try {} catch(...){}阻止因为lua脚本错误而导致的问题发生,感谢 lovesmiles

#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[] )
{
	try
	{
		L = luaL_newstate();
		luaL_openlibs(L);
		int iError = luaL_dofile(L, "test.lua");

		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);
	}
	catch (...)
	{
		printf("Error calling lua function error");
	}

	getchar();

	return 0;
}
  • 打赏
  • 举报
回复
lua_close(L);确实有点问题 正常的话,执行到这里就结束了:

if (lua_pcall(L, 0, 0, 0))
    {
        printf("Error calling lua function error");
    }
看看错误是不是这造成的: lua_pcall 如果是那就是你lua_close(L);造成的错误
勤奋的小游侠 2014-09-29
  • 打赏
  • 举报
回复
lua_close为什么你的程序会有两个? 在window下编程,将所有的访问lua的操作用try catch包起来,不让异常抛出,可以阻止程序崩溃。

64,651

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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