http://pastebin.com/VMgD3GZf
Spoiler
function class(obj)
obj = obj or {}
obj.init = obj.init or function() end
function obj:new(...)
local instance = setmetatable({__class = obj}, {__index = obj})
return instance, instance:init(...)
end
function obj:extend(t)
t = t or {}
for k,v in pairs(obj) do
if not t[k] then
t[k] = v
end
end
return class(t)
end
return setmetatable(obj, {__call = obj.new})
end
Classes are created by calling the class method.
MyClass = class{
some = 'vars';
a = 1;
b = 2;
c = 3;
}
-- Class variables are optional
MyClass = class()
MyClass.some = 'vars'
MyClass.a = 1
MyClass.b = 2
MyClass.c = 3
To create an instance, just call the class table.
obj = MyClass()
print(obj.a, obj.b, obj.c) --> 123
In the class, the :init() method is called when you create a class. You can use this to set variables at instance creation.
MyClass = class()
function MyClass:init(name)
self.name = name or 'NoName'
end
obj = MyClass('LUAAA')
print(obj.name) --> LUAAA
Inheritance is done by using the :extend() method on classes.
Parent = class{
foo = 'bar';
}
Child = Parent:extend{
bar = 'baz';
}
print(Child.foo) --> bar
print(Child.bar) --> baz
Finally, instances store their parent class in the __class variable, so you can check the types of certain instances.
Object = class()
obj = Object()
print(obj.__class == Object) --> true
As a usage example, here are some silly classes.
Thing = class()
function Thing:speak()
print 'I am a thing.'
end
Organism = Thing:extend{
kind = '';
}
function Organism:init(kind)
self.kind = kind or self.kind
end
function Organism:speak()
Thing.speak(self)
print 'A living thing, in fact.'
print('I am a '..self.kind)
end
Person = Organism:extend{
name = '';
kind = 'human';
}
function Person:init(name)
self.name = name or self.name
end
function Person:speak()
Organism.speak(self)
print('My name is '..self.name)
end
unknown = Thing()
unknown:speak() --> I am a thing.
frog = Organism('frog')
frog:speak()
--> I am a thing.
--> A living thing, in fact.
--> I am a frog
bob = Person('Bob')
bob:speak()
--> I am a thing.
--> A living thing, in fact.
--> I am a human
--> My name is Bob
Hopefully this'll teach you a thing or two about good ol' OO. :)/>/>/>/>/>