lua-users home
lua-l archive

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



On Jun 27, 2008, at 10:48 PM, Jan Schütze wrote:

It would be cool, if that would be possible with error+pcall somehow!

Syntax sugar aside, it's rather straightforward to roll your own try/ catch implementation according to your needs/circumstances, e.g.:

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

    return function( catch )
local someResults = { pcall( aFunction, unpack( someArguments, 1, aLength ) ) }
        local aStatus = someResults[ 1 ]

        if aStatus == true then
            return unpack( someResults, 2, table.maxn( someResults ) )
        else
            local anException = someResults[ 2 ]

            if catch ~= nil then
return catch( anException, aFunction, unpack( someArguments, 1, aLength ) )
            end

            return nil, anException
        end
    end
end

Usage example:

local function catch( anException, ... )
    print( anException, ... )
end

local function Test( aValue )
    error( 'panic! ' .. aValue )
end

try( Test, 'hello' )( catch )

print( 'Done' )