Skip to content
Lua

OOP com Herança

Implementar herança de classes usando metatables.

#oop#inheritance#class

Code

lua
-- 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