lua-users home
lua-l archive

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


The simplest answer is probably a weak ref object. You can build these as
follows (untested code here):

    local weakRefMeta = { __mode = "kv" }

    function makeWeakRef( obj )
        return setmetatable( { object = obj }, weakRefMeta )
    end

    function derefWeakRef( ref )
        assert( getmetatable( ref ) == weakRefMeta  )
        return ref.object
    end

Notes:

* This would be more efficient if implemented using an array index instead
of a table -- i.e., ref[ 1 ] instead of ref.object.

* The paranoid may want to protect the metatable and go to some trouble to
protect entry inside the weak ref table.

* One probably wants to cache weak refs so that makeWeakRef will return an
existing reference for an object if one already exists.

* One might want to define derefWeakRef so that it simply returns the
parameter if it isn't a weak ref instead of signaling an error.


You can then maintain a sorted array of pairs consisting of a priority and a
weak ref to the item. (More efficient but less clear, store the priorities
and weak item refs at sequential locations in one flat array.)

When you send a message, scan the array and compact out any entries where
the item reference has gone to nil.

Mark

P.S. This suggests the addition of a weak ref type to Lua. The semantics of
such a type should be that it gets dereferenced for table access, calling,
and message sends. One can implement this in pure Lua by adding metamethods
to the above code but they could probably be handled more efficiently in the
core.