c++不能捕捉lua异常
C++ not catching lua exceptions
我有一个用luabind绑定到Lua的c++程序。我目前正在测试lua和luabind必须提供的错误处理方法,以便帮助调试lua脚本。目标是让luabind或lua在出现语法错误和编程错误时抛出异常,以便我可以调试和纠正它们。
现在,问题是下面的脚本只是停止执行,没有任何错误消息或异常被抛出,所以在一个更大的程序中,我不知道问题在哪里,甚至不知道是否有问题。
以下是相关的代码片段:
Lua:(start.lua)
--complete file shown, this is meant to test the error handling of the C++ program
print("This is valid")
print(1234)
bad_function()
a = "meow"
b = 7
c = a + b
c++: Engine *callbackEngine;
int theCallback(lua_State *L) //This is so I can use my own function as an
//exception handler, pcall_log()
{
return callbackEngine->pcall_log(L);
}
void Engine::Run()
{
luabind::set_pcall_callback(&theCallback); //my own callback function,
//redirects to
//pcall_log() below
try {
luaL_dofile(L, "scripts/start.lua");
}
catch(luabind::error &sError) { //This never gets executed, noted by breakpoints
theCallback(L);
}
//etc...code not shown
int Engine::pcall_log(lua_State *L)
{
lua_Debug d;
lua_getstack( L,1,&d);
lua_getinfo( L, "Sln", &d);
lua_pop(L, 1);
stringstream ss;
ss.clear();
ss.str("");
ss << d.short_src;
ss << ": ";
ss << d.currentline;
ss << ": ";
if ( d.name != 0)
{
ss << d.namewhat;
ss << " ";
ss << d.name;
ss << ") ";
}
ss << lua_tostring(L, -1);
logger->log(ss.str().c_str(),ELL_ERROR);
return 1;
}
下面是运行的输出:
This is valid
1234
脚本停止运行,而不是像我预期的那样抛出异常。是否有一种方法可以控制lua何时抛出异常或其他方法来处理错误?我设置了日志记录函数来产生调试信息,但是断点显示上面的catch语句没有被执行。
谢谢!
如果你想通过Luabind加载Lua脚本,那么你不能使用luaL_dofile
或其他常规Lua函数来完成它。你必须使用Luabind函数。它看起来就像这样:
namespace lb = luabind;
int luaError = luaL_loadfile(pLuaState, "scripts/start.lua");
//Check for errors
lb::object compiledScript(lb::from_stack(pLuaState, -1));
lb::call_function<void>(compiledScript); //Call the script.
lua_pop(pLuaState, 1); //Remove the script from the stack. It's stored in our luabind::object
luaL_dofile()
不是Luabind的一部分,所以我不会期望它有任何Luabind异常。当Luabind本身从Lua调用某些东西(使用pcall()
)时,您设置的处理程序被使用/传递。luaL_dofile()
是基本Lua代码的一部分(L后缀将其标记为简化调用的库包装器)和普通C,因此您必须在调用后做自己的错误处理(从未使用Lua/Luabind异常)。
未经测试,但以下代码应该执行您期望代码执行的操作:
if(!luaL_doFile(L, "scripts/start.lua"))
theCallback(L);
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- C++Lua用户数据扰乱了Mathfu浮点值
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- Lua toString 异常用于布尔值
- c++不能捕捉lua异常
- 为什么当我的lua代码抛出错误时,我无法捕获luabind::error异常?