iscallable

iscallable

function iscallable( var ) --> res

Description

This function checks if var is callable through the standard function call syntax.

Parameters

var

Variable that should be checked.

Return Values

res

true if the argument can be callad through the standard function call syntax, otherwise false.

Code

local function iscallable_rec( mask, i )

   if "function" == type( i ) then return true end

   local mt = getmetatable( i )
   if not mt then return false end
   local callee = mt.__call
   if not callee then return false end

   if mask[ i ] then return false end
   mask[ i ] = true

   return iscallable_rec( mask, callee )
end

--ZFUNC-iscallable-v0
local function iscallable( var ) --> res
   return iscallable_rec( {},  var )
end

return iscallable

Examples

local t = require "taptest"
local iscallable = require "iscallable"

t( iscallable( 0 ),              false )
t( iscallable( "" ),             false )
t( iscallable( true ),           false )
t( iscallable( {} ),             false )
t( iscallable( function() end ),  true )

local calltab_a = {}
setmetatable( calltab_a, { __call = function() end } )

t( iscallable( calltab_a ), true )

local calltab_b = {}
setmetatable( calltab_b, { __call = calltab_a } )

t( iscallable( calltab_b ), true )

local rectab_a = {}
local rectab_b = {}
setmetatable( rectab_a, { __call = rectab_b } )
setmetatable( rectab_b, { __call = rectab_a } )

t( iscallable( rectab_b ), false )

t()