Self referencing userdata and garbage collection

Posted by drtwox on Stack Overflow See other posts from Stack Overflow or by drtwox
Published on 2010-05-02T23:44:25Z Indexed on 2010/05/02 23:48 UTC
Read the original article Hit count: 226

Filed under:

Because my userdata objects reference themselves, I need to delete and nil a variable for the garbage collector to work.

Lua code:

obj = object:new()
-- 
-- Some time later
obj:delete()  -- Removes the self reference
obj = nil     -- Ready for collection

C Code:

typedef struct {
    int self; // Reference to the object
    // Other members and function references removed
} Object;

// Called from Lua to create a new object
static int object_new( lua_State *L ) {
    Object *obj = lua_newuserdata( L, sizeof( Object ) );

    // Create the 'self' reference, userdata is on the stack top
    obj->self = luaL_ref( L, LUA_REGISTRYINDEX );

    // Put the userdata back on the stack before returning
    lua_rawgeti( L, LUA_REGISTRYINDEX, obj->self );

    // The object pointer is also stored outside of Lua for processing in C

    return 1;
}

// Called by Lua to delete an object
static int object_delete( lua_State *L ) {
    Object *obj = lua_touserdata( L, 1 );

    // Remove the objects self reference
    luaL_unref( L, LUA_REGISTRYINDEX, obj->self );

    return 0;
}

Is there some way I can set the object to nil in Lua, and have the delete() method called automatically? Alternatively, can the delete method nil all variables that reference the object? Can the self reference be made 'weak'?

© Stack Overflow or respective owner

Related posts about lua