]>
Commit | Line | Data |
---|---|---|
a098bb43 CP |
1 | -- class.lua |
2 | -- Compatible with Lua 5.1 (not 5.0). | |
3 | function class(base,ctor) | |
4 | local c = {} -- a new class instance | |
5 | if not ctor and type(base) == 'function' then | |
6 | ctor = base | |
7 | base = nil | |
8 | elseif type(base) == 'table' then | |
9 | -- our new class is a shallow copy of the base class! | |
10 | for i,v in pairs(base) do | |
11 | c[i] = v | |
12 | end | |
13 | c._base = base | |
14 | end | |
15 | -- the class will be the metatable for all its objects, | |
16 | -- and they will look up their methods in it. | |
17 | c.__index = c | |
18 | ||
19 | -- expose a ctor which can be called by <classname>(<args>) | |
20 | local mt = {} | |
21 | mt.__call = function(class_tbl,...) | |
22 | local obj = {} | |
23 | setmetatable(obj,c) | |
24 | if ctor then | |
25 | ctor(obj,...) | |
26 | else | |
27 | -- make sure that any stuff from the base class is initialized! | |
28 | if base and base.init then | |
29 | base.init(obj,...) | |
30 | end | |
31 | end | |
32 | return obj | |
33 | end | |
34 | c.init = ctor | |
35 | c.is_a = function(self,klass) | |
36 | local m = getmetatable(self) | |
37 | while m do | |
38 | if m == klass then return true end | |
39 | m = m._base | |
40 | end | |
41 | return false | |
42 | end | |
43 | setmetatable(c,mt) | |
44 | return c | |
45 | end | |
46 |