مۆدیوول:fun/trycall
ڕواڵەت
"بەڵگەدارکردنی ئەم مۆدیوولە دەکرێ لە مۆدیوول:fun/trycall/docدا دروست بکرێ"
local fun_is_callable_module = "Module:fun/isCallable"
local error = error
local format = string.format
local pcall = pcall
local type = type
local function is_callable(...)
is_callable = require(fun_is_callable_module)
return is_callable(...)
end
local function catch_values(obj, success, ...)
if success then
return success, ...
-- Error message will only take this exact form if `obj` is not callable,
-- because it will contain a traceback if it was thrown further up the
-- stack.
elseif (...) == format("attempt to call a %s value", type(obj)) then
return false
end
return error(...)
end
--[==[
A special form of {pcall()}, which returns {true} plus the result value(s) if {obj} is callable, or {false} if it isn't. Errors that occur within the called function are not protected.]==]
return function(obj, ...)
local callable = is_callable(obj, true)
if callable then
return true, obj(...)
elseif callable == false then
return false
end
-- If `callable` is nil, there's a protected metatable, so there's no way to
-- check without doing a protected call.
return catch_values(obj, pcall(obj, ...))
end