lua-users home
lua-l archive

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



On Jan 21, 2009, at 12:17 AM, Leo Razoumov wrote:

How to achieve such assurances short of wrapping everything else in a pcall (xpcall)?

What's wrong with pcall?

What about something along these lines.:

Try( Function, ... )( Catch, Finalize )

Example:

local function Try( aFunction, ... )
    local someArguments = { ... }
    local aLength = select( "#", ... )

    return function( aCatch, aFinal )
local someResults = { pcall( aFunction, unpack( someArguments, 1, aLength ) ) }
        local aStatus = someResults[ 1 ]
        local anException = someResults[ 2 ]

        if not aStatus and aCatch then
            aCatch( anException, unpack( someArguments, 1, aLength ) )
        end

        if aFinal then
            aFinal( unpack( someArguments, 1, aLength ) )
        end

        if not aStatus then
            return nil, anException
        end

        return unpack( someResults, 2, table.maxn( someResults ) )
    end
end

local function Do( aPath )
    print( 'Do', aPath )

    error( 'Oooops!', 2 )

    return 1
end

local function Catch( anException, aPath )
    print( 'Catch', anException, aPath )
end

local function Finalize( aPath )
    print( 'Finalize', aPath )
end

print( Try( Do, '/dev/null' )( Catch, Finalize ) )

> Do	/dev/null
> Catch	Oooops!	/dev/null
> Finalize	/dev/null
> nil	Oooops!

Cheers,

--
PA.
http://alt.textdrive.com/nanoki/