【问题标题】:Lua set default error handlerLua 设置默认错误处理程序
【发布时间】: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 函数中,该函数会自动执行此设置,但我有两个问题:

  1. 这种方法是否容易在 pcall 之前(或内部)被更复杂的堆栈操作破坏? (我还不是非常精通 Lua 堆栈)

  2. 1234563全局更改 Lua 状态的默认错误处理程序?

我看到lua_pcallk 有一些errfunc == 0 的代码,但它似乎不可配置。我们可以破解 Lua 实现来手动更改默认值,但希望避免这种情况。

我们使用的是 Lua 5.3。谢谢。

【问题讨论】:

    标签: c exception error-handling lua


    【解决方案1】:

    您的基本方法是正确的,但是您缺少lua_remove(而不是lua_pop)并且您的堆栈索引是错误的。试试这个:

    int lua_mypcall( lua_State* L, int nargs, int nret ) {
      /* calculate stack position for message handler */
      int hpos = lua_gettop( L ) - nargs;
      int ret = 0;
      /* push custom error message handler */
      lua_pushcfunction( L, my_error_handler );
      /* move it before function and arguments */
      lua_insert( L, hpos );
      /* call lua_pcall function with custom handler */
      ret = lua_pcall( L, nargs, nret, hpos );
      /* remove custom error message handler from stack */
      lua_remove( L, hpos );
      /* pass return value of lua_pcall */
      return ret;
    }
    

    【讨论】:

    • 谢谢,这行得通!您对更改默认处理程序有什么想法吗?我认为它不再那么重要了,因为这是 lua_pcall 的替代品(至少在 C 端)
    • 除非您想在无法重新编译的第三方模块中使用新的默认错误处理程序,否则我不会考虑修改 Lua 内部结构。事情也会有点混乱,因为您必须修改 lua_pcallklua_pcall 的可屈服版本)。
    • 啊,很好,我没有考虑过外部 lua 模块。再次感谢!
    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多