annotate class.lua @ 11:d2cbfe498c4d

first beta
author Jay Bird <a4blank@yahoo.com>
date Sat, 04 Dec 2010 05:53:52 +0300
parents f93b554bb7cf
children
rev   line source
a4blank@10 1 -- class.lua
a4blank@10 2 -- taken from http://lua-users.org/wiki/SimpleLuaClasses
a4blank@10 3 -- Compatible with Lua 5.1 (not 5.0).
a4blank@10 4 function class(base, init)
a4blank@10 5 local c = {} -- a new class instance
a4blank@10 6 if not init and type(base) == 'function' then
a4blank@10 7 init = base
a4blank@10 8 base = nil
a4blank@10 9 elseif type(base) == 'table' then
a4blank@10 10 -- our new class is a shallow copy of the base class!
a4blank@10 11 for i,v in pairs(base) do
a4blank@10 12 c[i] = v
a4blank@10 13 end
a4blank@10 14 c._base = base
a4blank@10 15 end
a4blank@10 16 -- the class will be the metatable for all its objects,
a4blank@10 17 -- and they will look up their methods in it.
a4blank@10 18 c.__index = c
a4blank@10 19
a4blank@10 20 -- expose a constructor which can be called by <classname>(<args>)
a4blank@10 21 local mt = {}
a4blank@10 22 mt.__call = function(class_tbl, ...)
a4blank@10 23 local obj = {}
a4blank@10 24 setmetatable(obj,c)
a4blank@10 25 if class_tbl.init then
a4blank@10 26 class_tbl.init(obj,...)
a4blank@10 27 else
a4blank@10 28 -- make sure that any stuff from the base class is initialized!
a4blank@10 29 if base and base.init then
a4blank@10 30 base.init(obj, ...)
a4blank@10 31 end
a4blank@10 32 end
a4blank@10 33 return obj
a4blank@10 34 end
a4blank@10 35 c.init = init
a4blank@10 36 c.is_a = function(self, klass)
a4blank@10 37 local m = getmetatable(self)
a4blank@10 38 while m do
a4blank@10 39 if m == klass then return true end
a4blank@10 40 m = m._base
a4blank@10 41 end
a4blank@10 42 return false
a4blank@10 43 end
a4blank@10 44 setmetatable(c, mt)
a4blank@10 45 return c
a4blank@10 46 end