lua-users home
lua-l archive

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


> I usually delay setting the metatable until the object is in a defined
> state, which is hard to do with this idiom. If the constructor of the object
> throws a C++ exception and you catch it the "__gc" routine  the metatable
> refers to may call the destructor, which is a bad idea because the
> constructor failed.

You are right. But there is a simple workaround for this problem.
As Pablo Pissanetzky already mentioned, you also need a matching
delete operator to deal with exceptions.
That can me written as (untested) :

void operator delete( void* ptr, lua_State * L, const char* metaname )
{
 lua_pushnil(L);
 lua_setmetatable(L, -2);
}

This delete overload will only be called if an exception occurs inside
the constructor.
Providing that the constructor does not itself deal with the Lua
state, the userdata is still on the top of the stack when the function
is called, and it is easy to invalidate the metatable *before* the
__gc metamethod could be called.