feat(class): recursive instanceOf and isClass method

This commit is contained in:
Linden
2024-03-11 11:21:07 +11:00
parent de49dff9b0
commit 92dc3688f8

View File

@@ -15,7 +15,9 @@ local function assertType(id, var, expected)
local received = type(var)
if received ~= expected then
error(("expected %s %s to have type '%s' (received %s)"):format(type(id) == 'string' and 'field' or 'argument', id, expected, received), 3)
error(
("expected %s %s to have type '%s' (received %s)"):format(type(id) == 'string' and 'field' or 'argument', id,
expected, received), 3)
end
return true
@@ -38,10 +40,23 @@ function mixins.new(class, obj)
end
---Checks if an object is an instance of the given class.
function mixins.instanceOf(obj, class)
function mixins.isClass(obj, class)
return getmetatable(obj) == class
end
---Checks if an object is an instance or derivative of the given class.
function mixins.instanceOf(obj, class)
local mt = getmetatable(obj)
while mt do
if mt == class then return true end
mt = getmetatable(mt)
end
return false
end
---Creates a new class.
---@todo add inherited types for new/private/init fields (not yet supported by lls)
---@param name string