Module:fun/xpcall
Documentation for this module may be created at Module:fun/xpcall/doc
local xpcall = xpcall
-- In Lua 5.2+, xpcall() can handle arguments natively, so return the
-- built-in version if the argument passed to the test function is returned.
if select(2, xpcall(function(v)
return v -- 1 if xpcall() passes arguments, or nil if not
end, xpcall, 1)) == 1 then
return xpcall
end
local table_pack_module = "Module:table/pack"
local unpack = unpack or table.unpack -- Lua 5.2 compatibility
local function pack(...)
pack = require(table_pack_module)
return pack(...)
end
-- Smuggle the function and arguments in via upvalues. There is no risk of
-- collisions across stack levels, because in any given call they are set
-- before being accessed, then accessed and reset to nil before calling `func`.
local _func, _args
local function call()
local func, args = _func, _args
_func, _args = nil, nil
return func(unpack(args, 1, args.n))
end
--[==[
A version of {xpcall} which takes any arguments to be given to {func} as additional arguments after the error handler.
This fixes a deficiency in the standard version of {xpcall}, which is not able to handle arguments to be given to {func}, and brings it in line with {pcall}.]==]
return function(func, err_handler, ...)
_func, _args = func, pack(...)
return xpcall(call, err_handler)
end