C++ 没有捕获 lua 异常

标签 c++ exception lua luabind

我有一个使用 luabind 绑定(bind)到 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

关于C++ 没有捕获 lua 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6909335/

相关文章:

c++ - std::function 的异常安全

Python Tornado gen.engine异常处理

c++ - 在 C++ 中处理 CPU 异常

vb.net - 从 'DBNull'类型到 'Date'类型的转换无效

function - Lua十进制符号?

Lua 尝试调用一个 nil 值的方法

templates - Pandoc lua过滤器在文档末尾移动图像标题

c++ - MFC:将 GetContextMenuManager()->ShowPopup 与 Office2007 视觉对象一起使用时出现延迟

c++ - sugar all() 行的 Rcpp 错误

c++ - 如何使用惰性传播实现线段树?