Stack unwinding in C++ when using Lua

倖福魔咒の 提交于 2019-12-09 16:45:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4005865/stack-unwinding-in-c-when-using-lua

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!