代码之家  ›  专栏  ›  技术社区  ›  deft_code

使用Lua时,C++中的堆栈展开

  •  7
  • deft_code  · 技术社区  · 15 年前

    我最近偶然发现了这个C++/Lua错误。

    int function_for_lua( lua_State* L )
    {
       std::string s("Trouble coming!");
       /* ... */
       return luaL_error(L,"something went wrong");
    }
    

    错误在于 luaL_error 使用 longjmp ,因此堆栈从未展开,并且 s

    一个明显的解决方案是用异常编译C++模式的Lua。一、 然而,不能像Luabind那样需要标准的C ABI。

    // just a heads up this is valid c++.  It's called a function try/catch.
    int function_for_lua( lua_State* L )
    try
    {
       /* code that may throw Lua_error */
    }
    catch( Lua_error& e )
    {
       luaL_error(L,e.what());
    }
    

    所以我的问题是 function_for_lua 的堆栈已正确展开。出什么事了吗?

    1 回复  |  直到 15 年前
        1
  •  2
  •   GManNickG    15 年前

    如果我理解正确 Luabind reference .)

    因此,每当需要指示错误时,只要抛出一个标准异常:

    void function_for_lua( lua_State* L )
    {
        std::string s("Trouble coming!");
        /* ... */
    
        // translated into lua error
        throw std::runtime_error("something went wrong");
    }
    

    免责声明:我从未使用过Lubind。