简体   繁体   English

使用Lua时在C ++中进行堆栈展开

[英]Stack unwinding in C++ when using Lua

I recently stumbled into this this C++/Lua error 我最近偶然发现了这个C ++ / Lua错误

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. 错误是luaL_error使用longjmp ,因此堆栈永远不会被解除,并且s永远不会被破坏,泄漏内存。 There are a few more Lua API's that fail to unwind the stack. 还有一些Lua API无法解开堆栈。

One obvious solution is to compile Lua in C++ mode with exceptions. 一个显而易见的解决方案是在C ++模式下编译Lua,但有异常。 I, however, cannot as Luabind needs the standard C ABI. 然而,我不能像Luabind那样需要标准的C ABI。

My current thought is to write my own functions that mimic the troublesome parts of the Lua API: 我目前的想法是编写我自己的函数,模仿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. 所以我的问题是: function_for_lua的堆栈是否正确解开。 Can something go wrong? 可能会出错吗?

If I understand correctly, with Luabind functions that throw exceptions are properly caught and translated anyway. 如果我理解正确的话,使用Luabind函数可以正确地捕获和翻译抛出异常。 (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. 免责声明:我从未使用过Lubind。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM