a4blank@10: -- class.lua a4blank@10: -- taken from http://lua-users.org/wiki/SimpleLuaClasses a4blank@10: -- Compatible with Lua 5.1 (not 5.0). a4blank@10: function class(base, init) a4blank@10: local c = {} -- a new class instance a4blank@10: if not init and type(base) == 'function' then a4blank@10: init = base a4blank@10: base = nil a4blank@10: elseif type(base) == 'table' then a4blank@10: -- our new class is a shallow copy of the base class! a4blank@10: for i,v in pairs(base) do a4blank@10: c[i] = v a4blank@10: end a4blank@10: c._base = base a4blank@10: end a4blank@10: -- the class will be the metatable for all its objects, a4blank@10: -- and they will look up their methods in it. a4blank@10: c.__index = c a4blank@10: a4blank@10: -- expose a constructor which can be called by () a4blank@10: local mt = {} a4blank@10: mt.__call = function(class_tbl, ...) a4blank@10: local obj = {} a4blank@10: setmetatable(obj,c) a4blank@10: if class_tbl.init then a4blank@10: class_tbl.init(obj,...) a4blank@10: else a4blank@10: -- make sure that any stuff from the base class is initialized! a4blank@10: if base and base.init then a4blank@10: base.init(obj, ...) a4blank@10: end a4blank@10: end a4blank@10: return obj a4blank@10: end a4blank@10: c.init = init a4blank@10: c.is_a = function(self, klass) a4blank@10: local m = getmetatable(self) a4blank@10: while m do a4blank@10: if m == klass then return true end a4blank@10: m = m._base a4blank@10: end a4blank@10: return false a4blank@10: end a4blank@10: setmetatable(c, mt) a4blank@10: return c a4blank@10: end