Try

From OpenEUO
Revision as of 21:27, 1 November 2010 by Ximan (Talk | contribs) (Created page with "== 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 resul...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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, then the function hndlr is called with a single argument, eref, a numeric reference to an error table that can be retrieved via geterror. If the handler raises an error (either an intentional reraising of the original, or a novel error), then further error handling is passed to the library and accomplished according to the reporting mode in effect: reraise (default), inlined, or using a library-wide user specified callback function. See [error reporting modes] for more information.

try is intended to be used to handle errors in user functions. In most instances, try should not be used directly on library calls, as they already have an internal form of try applied to them. 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