· 7 years ago · Dec 02, 2018, 04:20 PM
1-- Class.lua
2-- Compatible with Lua 5.1 (not 5.0).
3--
4-- Modified to use a metatable to reference base objects instead
5-- or performing shallow copies. This means smaller classes that
6-- are a bit more dynamic at the expence of some performance.
7
8-- NOTE, this class definition is ONLY defined for the current environment, NOT the _G environment so it is totally safe to use with other plugins, even those that depend on older Turbine samples
9class = function( base )
10 if ( base ~= nil ) then
11 local baseType = type( base );
12
13 if ( baseType ~= 'table' ) then
14 error( "Base class is not a table. Base class was a " .. baseType );
15 end
16 end
17
18 -- The class definition table. Contains all of the actual class
19 -- methods, constructor, and an IsA function automatically
20 -- provided.
21 local c = { };
22
23 c.base = base;
24 c.IsA = function( self, klass )
25 local m = getmetatable( self );
26
27 while m do
28 if m == klass then
29 return true;
30 end
31
32 m = m.base;
33 end
34
35 return false;
36 end
37
38 -- The class definition metatable. This is used to hook up
39 -- base classes and then to register a call handler that is
40 -- used to construct new instances of the class.
41 local mt = { };
42 mt.__index = base;
43
44 mt.__call = function( class_tbl, ... )
45 if ( class_tbl.Abstract ) then
46 error "Abstract class cannot be constructed.";
47 end
48
49 -- Create the new class instance.
50 local instance = { };
51 setmetatable( instance, { __index = c } );
52
53 -- Invoke the constructor if it exists.
54 if ( ( instance.Constructor ~= nil ) and ( type( instance.Constructor ) == 'function' ) ) then
55 instance:Constructor( ... );
56 end
57
58 return instance;
59 end
60
61 setmetatable( c, mt );
62 return c;
63end