[英]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语句未得到执行。
谢谢!
luaL_dofile()
不属于Luabind,所以我不希望它有任何Luabind异常。 当Luabind本身从Lua调用某些东西(使用pcall()
)时,将使用/传递您设置的处理程序。 luaL_dofile()
是基本Lua代码的一部分(L后缀将其标记为库包装以简化调用)和普通C,因此您必须自己进行错误处理(老实说,Lua / Luabind从未使用过异常)通话后。
未经测试,但是下面的代码应该可以完成您期望的代码:
if(!luaL_doFile(L, "scripts/start.lua"))
theCallback(L);
如果要通过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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.