Code: Select all
local mt = {__index = function(self, key) return self.__baseClass[key] end, __call = function(self, ...) return self:new(...) end}
local class = setmetatable({ __baseClass = {}, __type = "class" }, mt)
function class:new(...)
local arg, cls = {...}, {__baseClass = self}
setmetatable(cls, getmetatable(self))
if type(arg[1]) == "table" and arg[1].__type == "class" then
cls.__super, cls.__BaseClass = arg[1], arg[1]
setmetatable(cls, getmetatable(arg[1]))
end
if cls.init then cls:init(...) end
return cls
end
return class
Code: Select all
class = require "class"
-- Defining a class
Person = class()
-- Setting init function
function Person:init(name, age)
self.name, self.age = name, age
end
-- Class method
function Person:speak()
print("Hi my name is " .. self.name .. " and i am " .. self.age .. " years old.")
end
-- Inheritance
-- Definding a child class
Worker = class(Person)
-- Overwriting the parents class init function
function Worker:init(name, age, occupation, salary)
self.__super.init(self, name, age) -- Calling the parents class init function because i just overwrote it
-- Worker specific properties
self.occupation, self.salary = occupation, salary
end
-- Same deal for the Worker's speak function
function Worker:speak()
self.__super.speak(self)
print("I work as a " .. self.occupation .. " for a salary of $" .. self.salary)
end
p1 = Person("Joe", 23)
p2 = Worker("Alex", 34, "Doctor", 100)
p1:speak()
p2:speak()