[meta] Improve isinstance().

* Handle nil
* Use rawequal() instead of plain ==
This commit is contained in:
Lorenzo Cogotti 2022-11-06 17:32:55 +01:00
parent 62d22658b3
commit 99fde174df
1 changed files with 7 additions and 3 deletions

View File

@ -9,16 +9,20 @@ local meta = {}
--- Test whether 'obj' is an instance of the given class 'cls'.
--
-- @tparam table obj
-- @tparam table cls
-- Note that nil is the only instance of the nil class.
--
-- @tparam table obj object instance to be tested
-- @tparam table cls class argument
-- @treturn bool
function meta.isinstance(obj, cls)
if rawequal(cls, nil) then return rawequal(obj, nil) end
repeat
local m = getmetatable(obj)
if rawequal(m, cls) then return true end
obj = m
until obj == nil
until rawequal(obj, nil)
return false
end