开发者

Stack unwinding in C++ when using Lua

开发者 https://www.devze.com 2023-01-22 05:06 出处:网络
I recently stumbled into this this C++/Lua error int function_for_lua( lua_State* L ) { std::string s(\"Trouble coming!\");

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消