Module:fun/isCallable: Difference between revisions
Jump to navigation
Jump to search
m Protected "Module:fun/isCallable": Highly visible template/module ([Edit=Allow only template editors and administrators] (indefinite) [Move=Allow only template editors and administrators] (indefinite)) |
Created page with "local table_get_metamethod_module = "Module:table/getMetamethod" local require = require local type = type local function get_metamethod(...) get_metamethod = require(table_get_metamethod_module) return get_metamethod(...) end --[==[ Return {true} if the input is a function or functor (an object which can be called like a function, because it has a {__call} metamethod). Note: if the input is an object with a {__call} metamethod, but this function is not able to fin..." |
||
| Line 1: | Line 1: | ||
local table_get_metamethod_module = "Module:table/getMetamethod" | local table_get_metamethod_module = "Module:table/getMetamethod" | ||
local require = require | local require = require | ||
local type = type | local type = type | ||
local function get_metamethod(...) | local function get_metamethod(...) | ||
| Line 34: | Line 28: | ||
-- `obj` is callable without actually calling it. | -- `obj` is callable without actually calling it. | ||
elseif not success then | elseif not success then | ||
if allow_maybe then | if allow_maybe then | ||
return nil | return nil | ||
Revision as of 09:15, 28 June 2025
Documentation for this module may be created at Module:fun/isCallable/doc
local table_get_metamethod_module = "Module:table/getMetamethod"
local require = require
local type = type
local function get_metamethod(...)
get_metamethod = require(table_get_metamethod_module)
return get_metamethod(...)
end
--[==[
Return {true} if the input is a function or functor (an object which can be called like a function, because it has a {__call} metamethod).
Note: if the input is an object with a {__call} metamethod, but this function is not able to find it because the object's metatable is protected with {__metatable}, then it will return {false} by default, or {nil} if the {allow_maybe} flag is set.]==]
return function(obj, allow_maybe)
if type(obj) == "function" then
return true
end
-- An object is callable if it has a __call metamethod, so try to get it
-- with get_metamethod().
local success, __call = get_metamethod(obj, "__call")
-- If this succeeds, `obj` will only be callable if the __call metamethod is
-- a function (i.e. it can't itself be a callable table), so don't recurse
-- to check it.
if __call and type(__call) == "function" then
return true
-- If not, then the metatable is protected, so it's not possible to know if
-- `obj` is callable without actually calling it.
elseif not success then
if allow_maybe then
return nil
end
end
return false
end