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

发布于 2024-09-28 22:13:47 字数 734 浏览 7 评论 0原文

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

I recently stumbled into this this C++/Lua error

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

The error is that luaL_error use longjmp, so the stack is never unwound and s is never destructed, leaking memory. There are a few more Lua API's that fail to unwind the stack.

One obvious solution is to compile Lua in C++ mode with exceptions. I, however, cannot as Luabind needs the standard C ABI.

My current thought is to write my own functions that mimic the troublesome parts of the 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());
}

So my question: Is function_for_lua's stack properly unwound. Can something go wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

十年不长 2024-10-05 22:13:47

如果我理解正确的话,无论如何,使用 Luabind 函数抛出异常都会被正确捕获和翻译。 (请参阅参考。)

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

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

    // translated into lua error
    throw std::runtime_error("something went wrong");
}


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

If I understand correctly, with Luabind functions that throw exceptions are properly caught and translated anyway. (See reference.)

So whenever you need to indicate an error, just throw a standard exception:

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

    // translated into lua error
    throw std::runtime_error("something went wrong");
}


Disclaimer: I've never used Lubind.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文