Stack unwinding in C++ when using Lua
Asked Answered
E

1

7

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?

Edgebone answered 23/10, 2010 at 20:14 Comment(1)
I'm confused when you mentioned Luabind. Luabind itself is a C++ library, but it looks like you're not using it anyway?Disjunction
S
2

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.

Surd answered 23/10, 2010 at 20:31 Comment(1)
@Armen: Gotta keep people on their toes.Surd

© 2022 - 2024 — McMap. All rights reserved.