32 lines of goodness
The Libary
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 all there is to it!! just 32 lines!!
Usage
slap the above libary in a file of your choose(maybe "32log.lua") and include it in your code using the require function
the basic syntax is as follows
class "ClassName" : extends(BaseClassName) {
memberName = nonNilValue;
}
once a class has been created you can create new instances of the class as follows
local myInstance = ClassName:new()
if you create a method named __init it can be used to as a constructor with new.
class "Vector" {
x = 0;
y = 0;
z = 0;
}
function Vector:__init(x, y, z)
self.x = x
self.y = y
self.z = z
end
function Vector:print()
print(self.x, self.y, self.z)
end
local vec = Vector:new(1, 0.5, 0.25)
vec:print()
what ever value you set a member to in the definition, it will act as a default value for the member. this works well with values like numbers and strings where they are always copied by value but tables can get a little tricky,
class "Foo" {
bar = {};
}
local foo = Foo:new()
foo.bar["foobar"] = 10;
local foo2 = Foo:new()
print(foo2.bar["foobar"])
classes inherit there parents default member values and meta-methods. you can also call a parents method that was overloaded in the derived class using the super member.
class "Base" {}
function Base:foobar()
print("foo")
end
class "Derived" : extends(Base) {}
function Derived:foobar()
self.supper.foobar(self)
print("bar")
end
See Also
post any questions you might have in the original post original post