Code: Select all
local mt_class = {}
function mt_class:extends(parrent)
self.super = parrent
setmetatable(mt_class, {__index = parrent})
parrent.__members__ = parrent.__members__ or {}
return self
end
local function define(class, members)
class.__members__ = class.__members__ or {}
for k, v in pairs(members) do
class.__members__[k] = v
end
function class:new(...)
local newvalue = {}
for k, v in pairs(class.__members__) do
newvalue[k] = v
end
setmetatable(newvalue, {__index = class})
if newvalue.__init then
newvalue:__init(...)
end
return newvalue
end
end
function class(name)
local newclass = {}
_G[name] = newclass
return setmetatable(newclass, {__index = mt_class, __call = define})
end
that's it
here is an example on how to use it
Code: Select all
--creates a class with 2 data members
class "Shape" {
width = 0;
height = 0;
}
--creates a constructor
function Shape:__init(a, b)
self.width = a
self.height = b
end
--creates a function that dose nothing useful,
function Shape:talk()
print("shapes can talk?")
end
--creates a class called rectanlge that inherts from Shape
class "Rectangle" : extends(Shape) {}
--constructor has already been inhierted, no need to make it
--overloads Shape:talk
function Rectangle:talk()
print("im a rectangle!!")
end
--new function to show how a sub-class can call it's parrents methods even if they have been overloaded
--if you need to call the parrent of a parrents method you can do self.super.super.method(self) and so on untill you have gone back sufficently far
function Rectangle:supertalk()
self.super.talk(self)
end
--create an area function that tells us the area of a rectangle
function Rectangle:area()
return self.width * self.height
end
--creates another class that inherits from shape, this time representing a triangle
class "Triangle" : extends(Shape) {}
function Triangle:area()
return self.width * self.height / 2
end
local rect = Rectangle:new(10, 10)
local tri = Triangle:new(10, 10)
print(rect:area())
print(tri:area())
print(rect:talk())
print(rect:supertalk())
you can see one of our resident lovers plugging his OO lib, middle class