instanceof and Type Introspection
Implement instanceof() checks by walking the class hierarchy.
What Is instanceof?
instanceof(obj, Class) checks whether an object is an instance of a specific class or any of its ancestors. It replaces Lua's raw type() for OOP systems.
Simple instanceof
Walk the metatable chain from the instance upward, looking for the target class.
local function instanceof(obj, cls)
if type(obj) ~= "table" then return false end
local mt = getmetatable(obj)
while mt do
if mt == cls then return true end
local parent = getmetatable(mt)
mt = parent and parent.__index
end
return false
endAll lessons in this course
- Base Class and Constructor Design
- Multi-Level Inheritance
- Mixin Composition and Interface Checks
- instanceof and Type Introspection