comparison class.lua @ 10:f93b554bb7cf

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