c++不能捕捉lua异常

C++ not catching lua exceptions

本文关键字:lua 异常 不能 c++      更新时间:2023-10-16

我有一个用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);