From 92dc3688f812c85b7b72748a72009024d12b01ff Mon Sep 17 00:00:00 2001 From: Linden <65407488+thelindat@users.noreply.github.com> Date: Mon, 11 Mar 2024 11:21:07 +1100 Subject: [PATCH] feat(class): recursive instanceOf and isClass method --- imports/class/shared.lua | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/imports/class/shared.lua b/imports/class/shared.lua index 6b4e56d..20548ce 100644 --- a/imports/class/shared.lua +++ b/imports/class/shared.lua @@ -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