c++ - 使用 Lua 时在 C++ 中展开堆栈

标签 c++ lua destructor stack-unwinding

我最近偶然发现了这个 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 的堆栈是否正确展开。会不会出什么问题?

最佳答案

如果我理解正确的话,使用 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。

关于c++ - 使用 Lua 时在 C++ 中展开堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005865/

相关文章:

c++ - 在析构函数中要破坏什么,不要破坏什么

c++ - 如何在不调用析构函数的情况下重新分配 vector ?

c++ - const char * 上的析构函数

c++ - 无法弄清楚为什么 while 循环是无限的

c++ - 谷歌模拟无法模拟带有模板化参数的方法

c++ - 从 lua 加载一个库

performance - 为什么 Lua 中的本地化函数更快?

lua - 如何检查lua表中嵌套的bool

c++ - 如何使用 Poco C++ HTTPSessionFactory

c++ - Qt检测计算机何时进入休眠状态?