简体   繁体   中英

Stack unwinding in C++ when using 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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