【发布时间】:2015-07-13 08:28:38
【问题描述】:
默认的lua_pcall 错误处理程序(从 Lua 5.3 开始)什么都不做,让异常消息保留在堆栈顶部。我们想改变这一点,所以除了lua_pcall失败时堆栈顶部的异常消息外,我们还能获得luaL_traceback回溯。
不幸的是,我认为这意味着我们需要在所有 pcall 下方插入错误处理程序。最稳健的做法似乎是这样的:
/* push function and arguments */
lua_pushstuff...
/* push error handler */
lua_pushcfunction(L, my_error_handler);
/* move the error handler just below the function and arguments */
lua_insert(L, -(number of args + 1));
if (lua_pcall(L, nargs, nresults, -(number of args + 1))) {
/* error here (my_error_handler was invoked) */
/* do something with lua_tostring(L, -1) */
}
/* afterwards, pop the error handler (it may be below return values) */
lua_pop(L, 1);
但这会在每个 pcall 中引入噪音(我们有很多,因为我们有一些从 C 异步调用的 Lua 回调)并且感觉有点重复。我认为这可以包含在一些 lua_mypcall 函数中,该函数会自动执行此设置,但我有两个问题:
这种方法是否容易在 pcall 之前(或内部)被更复杂的堆栈操作破坏? (我还不是非常精通 Lua 堆栈)
1234563全局更改 Lua 状态的默认错误处理程序?
我看到lua_pcallk 有一些errfunc == 0 的代码,但它似乎不可配置。我们可以破解 Lua 实现来手动更改默认值,但希望避免这种情况。
我们使用的是 Lua 5.3。谢谢。
【问题讨论】:
标签: c exception error-handling lua