0Pricing
Lua Academy · Lesson

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
end

All lessons in this course

  1. Base Class and Constructor Design
  2. Multi-Level Inheritance
  3. Mixin Composition and Interface Checks
  4. instanceof and Type Introspection
← Back to Lua Academy