lua-users home
lua-l archive

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


Taking Roberto's hint I've worked out weak references, at least on paper.

-John

p.s. I'm wondering about the Technical Notes... is this kind of content
suitable?

----

** Weak references for Lua **

Synopsis

    ref = weakref( val )
    -- ref is an object, use function call syntax to dereference it
    val = ref()


Implementation

    Function weakref is implemented in C.  It creates a userdata
    object. Only one value is needed as state (the number returned by
    lua_ref), so the userdata pointer itself can be used instead of
    allocating memory. The "function" tagmethod is set on the object,
    and when called it returns the result of lua_getref.  The "gc"
    tagmethod is also set on the object, so that lua_unref can be
    called to free the reference resource when the weak reference
    object is collected.


Where to from here

    Weak tables

        Using the interface above, it is possible to implement weak
        tables (from Lua).  A weak table works like any other table,
        except that for garbage collection it doesn't count as a
        reference of the values it holds.

        Actually the description above is technically for a "weak value
        hash". There are also variants known as "weak key hash"
        (strong reference to value is released when key is collected)
        and "doubly weak hash" (both value and key are weak).  These
        could be implemented also, but perhaps would require
        callbacks.


    Callbacks

        Again with help from C, it's possible to generate callbacks
        when the value pointed to by a weak reference is collected.
        This could be implemented by keeping a list of such references
        and then, using the end-of-garbage-collection hook, scan for
        references that have nil values.