lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi there,

How can one be sure that locally allocated memory will be released when an error occurs during the execution of some function of the Lua API? As in the following code, per example: `foo` is never deleted as an error occurs and the execution is tranfered back to `main`.

   int pmain( lua_State* L )
   {
      Foo* foo = new Foo;

      lua_pushstring( L, "This should be a table." );
      lua_pushstring( L, "The next line will cause a run-time error." );
      lua_gettable( L, -2 );

      delete foo;
      return 0;
   }

   int main()
   {
      lua_State* L = lua_open();
      lua_cpcall( L, pmain, 0 );
      lua_close(L);
      return 0;
   }

Looking at the Lua exception handling mechanism, I noticed that it is possible to redefine `L_THROW` and `L_TRY` via the `LUA_USEEXCEPTIONS` macro, so as to use exceptions and let compiler generate the necessary cleanup code. This way, one could safely wrap `foo` with something like `std::auto_ptr` and just don't worry about memory management anynore.

But I definitively don't want to change my Lua libraries and start using C++ to build them. So I was wondering how could that be done purely in Lua, possibly pushing `foo` somehow to the Lua stack as userdata and using its `__gc` metamethod... Any idea?

Socal