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

我最近遇到了这个 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 永远不会被销毁,从而导致内存泄露。还有一些其他的 Lua API 也存在堆栈未展开的情况。

一个明显的解决方案是以 C++ 模式编译 Lua,并使用异常。但我不能这样做,因为 Luabind 需要标准的 C ABI。

我的当前想法是编写自己的函数,模拟 Lua API 的一些麻烦部分:

// 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 的堆栈是否得到了正确的展开?会发生什么问题吗?

原文链接 https://stackoverflow.com/questions/4005865

点赞
stackoverflow用户87234
stackoverflow用户87234

如果我理解正确,使用Luabind时,会正确地捕捉并转换函数抛出的异常。(见参考文献。)

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

void function_for_lua( lua_State* L )
{
    std::string s("Trouble coming!");
    /* ... */

    // 转换为lua错误
    throw std::runtime_error("something went wrong");
}

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

2010-10-23 20:31:00