Try

From OpenEUO
Revision as of 21:33, 1 November 2010 by Ximan (Talk | contribs) (Description)

Jump to: navigation, search

Calling Convention

Call

local r[,...] = sl.try(func,hndlr)

Args

func is a function
hndlr is a function

Results

r1...rN   results returned from func
or
r1...rN   results returned from hndlr, if func raises an error
or
r1...rN   results returned from error handling callback, if set and enabled,
          and hndlr reraises the error (see below)
or
ERR, eref if hndlr reraises error and inline handling enabled (see below)

Usage Example

local sl = dofile(getinstalldir()..'/lib/simplelib.lua')
sl.slredirect('pi')
local f = function() local a  = {} a = a + 1 + 'a' return a end
local h = function(err)
  if type(err) == 'string' then
    return 'error '..tostring(err)
  else
    local e = sl.geterror(err)
    return e._errmsg
  end
end
print(sl.try(f,h))
 --> 'error ...\scripts\test00.lua:3: attempt to perform arithmetic on local 'a' (a table value)'

Description

try is provided as a library wrapper for pcall. If the provided function func executes without generating any errors then its results are mirrored as the results of the try call. If an error is raised within func, then the function hndlr is called with a single argument, err, either a numeric reference to an error table that can be retrieved via geterror, or a string description of the error. If hndlr raises an error (either an intentional reraising using error, or a novel error), then further error handling is passed to the library and accomplished according to the reporting mode in effect: reraise to system (default), inlined, or using a library-wide user specified callback function. The last two options are useful for designing scripts that fail gracefully (or, at least silently, lolz). See [error reporting modes] for more information.

try is intended to be used to handle errors in user functions that employ library methods. In most instances, try should not be used directly on library calls, as they already have an internal form of try applied to them, and this will simply multiply the number of error messages recorded. Notable exceptions are the luo, macro, and str table methods.

Upon Error

If try doesn't receive two valid functions as arguments, a library error is raised and handled according to the current redirection mode.

See Also

  • try