Skip to content
Lua

OOP with Inheritance

Implement class inheritance using metatables.

By EZ4Code Team
oopinheritanceclass

Code

-- Base class
local Animal = {}
Animal.__index = Animal

function Animal.new(name)
  local self = setmetatable({}, Animal)
  self.name = name
  return self
end

function Animal:speak()
  return self.name .. " makes a sound"
end

-- Derived class
local Dog = setmetatable({}, {__index = Animal})
Dog.__index = Dog

function Dog.new(name, breed)
  local self = Animal.new(name)  -- call parent constructor
  setmetatable(self, Dog)        -- override metatable
  self.breed = breed
  return self
end

function Dog:speak()  -- override
  return self.name .. " barks!"
end

function Dog:fetch()
  return self.name .. " fetches the ball"
end

-- Usage
local a = Animal.new("Cat")
local d = Dog.new("Rex", "Labrador")

print(a:speak())  -- "Cat makes a sound"
print(d:speak())  -- "Rex barks!"
print(d:fetch())  -- "Rex fetches the ball"

-- Type check
print(getmetatable(d) == Dog)             -- true
print(getmetatable(getmetatable(Dog).__index) == Animal)  -- inheritance chain

Explanation

Inheritance via chained metatables: setmetatable(Dog, {__index = Animal}) makes Dog lookups fall through to Animal. The derived constructor calls the parent constructor then reassigns the metatable. Methods are overridden by name. Use self (first param) — the : syntax sugar passes self automatically; obj:method() == obj.method(obj).

More Lua Snippets