···11+-- class.lua
22+-- Compatible with Lua 5.1 (not 5.0).
33+function class(base, init)
44+ local c = {} -- a new class instance
55+ if not init and type(base) == 'function' then
66+ init = base
77+ base = nil
88+ elseif type(base) == 'table' then
99+ -- our new class is a shallow copy of the base class!
1010+ for i,v in pairs(base) do
1111+ c[i] = v
1212+ end
1313+ c._base = base
1414+ end
1515+ -- the class will be the metatable for all its objects,
1616+ -- and they will look up their methods in it.
1717+ c.__index = c
1818+1919+ -- expose a constructor which can be called by <classname>(<args>)
2020+ local mt = {}
2121+ mt.__call = function(class_tbl, ...)
2222+ local obj = {}
2323+ setmetatable(obj,c)
2424+ if init then
2525+ init(obj,...)
2626+ else
2727+ -- make sure that any stuff from the base class is initialized!
2828+ if base and base.init then
2929+ base.init(obj, ...)
3030+ end
3131+ end
3232+ return obj
3333+ end
3434+ c.init = init
3535+ c.is_a = function(self, klass)
3636+ local m = getmetatable(self)
3737+ while m do
3838+ if m == klass then return true end
3939+ m = m._base
4040+ end
4141+ return false
4242+ end
4343+ setmetatable(c, mt)
4444+ return c
4545+end
4646+4747+return class