Наследование классов


Dog = {}

function Dog:new()
   newObj = { voice = 'wow-wow' }
   self.__index = self
   return setmetatable(newObj, self)
end

function Dog:makeSound()
   print('I say ' .. self.voice)
end

mrDog = Dog:new()
mrDog:makeSound()

-- Наследование (расширение)

LoudDog = Dog:new()

function LoudDog:makeSound()
  s = self.voice .. ' '
  print(s .. s .. s)
end

bigDog = LoudDog:new()
bigDog:makeSound()

И более продвинутая версия

Animal = {}

Animal = (function (...)
    local obj = { }
    obj = setmetatable(obj, {
        __index = Animal,
        __call = function(cls, ...)
            return cls:new(...)
        end
    })
    return obj
end)()

function Animal:new(init)
    local obj = { size = init or 1 }
    self.__index = self
    return setmetatable(obj, self)
end

function Animal:get_size()
    return self.size
end

function Animal:set_size(s)
    self.size=s
end

Dog = {}
(function (...)
    setmetatable(Dog, {
        __index = Animal,
        __call = function(cls, ...)
            return cls:new(...)
        end
    })
    return Dog
end)()

function Dog:new(s,a)
    local obj = Animal(s)
    obj.age = a
    self.__index = self
    return setmetatable(obj, self)
end

function Dog:dump()
    print(self.size..' '..self.age)
end

local a = Animal(10)
print( a:get_size() )
a:set_size(5)
print( a:get_size() )

local b = Dog(20,5)
print( b:get_size() )
b:dump()

local c = Dog(21,6)
print( c:get_size() )
c:dump()

b:dump()