lua-users home
lua-l archive

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


I started poking around but haven't finished building something inspired by
the reference counting autorelease pools in Apple's Cocoa. What Cocoa
provides is a stack of pools per thread. Calling autorelease on an object
adds it to the topmost pool. When a pool gets destroyed all of the objects
in the pool receive release messages which decrement their reference counts.
Furthermore, destroying a pool destroys all of the pools above it so one
generally doesn't need error handling code around pools.

This could readily be extended to handle arbitrary cleanup functions.

For example:

    local myFile = io.open( filePath )
    cleanup.push( function() myFile:close() )
    
    ... Do stuff with myFile, it will close when we next cleanup ...

Now, true, garbage collection would also close myFile, but that is less
predictable. If we want to be more aggressive about getting the file closed,
we use something like:

    local scope = cleanup.openscope()
    
    local myFile = io.open( filePath )
    cleanup.push( function() myFile:close() )
    
    ... Do stuff with myFile, it will close when we next cleanup ...

    cleanup.closescope( scope )

One could extend the existing pcall to bracket code with cleanup logic. This
wouldn't make pcall yield eligible, but would make it be more aggressive
about seeing the cleanup occurred.

The tricks/issues that I've noted in sketching out an implementation:

1. Determining the current thread since each thread needs its own stack of
cleanup scopes and then finding the stack for the thread.

2. Making sure that cleanup logic runs if a thread gets garbage collected.

Mark