Well, I did. This is 26loA, or 26 lines of AWESOME (I don't want to beat a dead horse with the "goodness" thing).
Code: Select all
local classes={}
local function new(tab,...)
local obj=setmetatable({},tab.mt or {})
getmetatable(obj).__index=tab
if obj.init then
obj:init(...)
end
return obj
end
function class(name)
local function add(tab)
classes[name]=setmetatable({},{__call=function(self,...) return new(tab,...) end,__index=tab})
_G[name]=classes[name]
end
return function(arg)
if type(arg)=="table" then
add(arg)
else
return function(tab)
add(setmetatable(tab,{__index=classes[arg]}))
end
end
end
end
Code: Select all
require 'OO' --assume it is OO.lua in top level
function love.load()
class "test" {
asdf=true;
init=function(self) self.asdf=false end;
mt={__newindex=function(self,i,v) print(i,v) rawset(self,i,v) end}
}
local o=test()
print(o.asdf) --init works!
o.asdf=true --mt works!
class "test2" "test" {
qwer=false;
}
local o2=test2()
print(o2.asdf) --inheritance works from the parent class!
o2.qwer=true; --mt inheritance works!
class "test3" "test2" {
zxcv=false;
method=function(self) self.zxcv=not self.zxcv end
}
local o3=test3()
print(o3.asdf) --can fetch everything above it!
o3:method() --methods work, everything is fine!
end