lua-users home
lua-l archive

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


You can also provide an explicit free operation to handle the
non-exceptional case.

Here's a rough outline of how one might handle this...

    Foo** fooHdl = lua_newuserdata( L, sizeof( Foo* ) );
        /* Push a proxy to hold the foo object. */

    pushFooMetatable( L );
        /* Push the metatable containing the GC metamethod. */

    lua_setmetatable( L, -2 );
        /* Set the metatable. */

    *fooHdl = FooLib_alloc();
        /* Allocate the foo. */

    /* Process the data, allocate return results in Lua, etc. */

    /* Success. Clean up fast. */

    Foo* foo = *fooHdl;
    *fooHdl = NULL;
    
    FooLib_free( foo );

The GC metamethod for Foo userdatas will check first for NULL before calling
FooLib_free.

Mark

on 7/1/06 8:20 AM, Matt Campbell at mattc@freedombox.cc wrote:

> Hello Andrew:
> 
> The correct solution is to wrap the library-allocated data in a
> userdatum whose __gc metamethod frees the data.  This way, the data is
> under the control of the Lua garbage collector.  Then you no longer have
> to explicitly free it at the end of your C function; just make sure the
> userdatum stays on the Lua stack.  And you'll know that the data will
> always eventually be freed when it's no longer needed, even if a Lua
> error occurred.  For more information, see the chapter on managing
> resources in the book _Programming in Lua_, the first edition of which
> is available at no charge online.