2
-- This is a simple OOP single-inheritance implementation based
3
-- on the one suggested by <Programming in Lua at http://www.lua.org/pil/16.html>.
4
-- One big difference from what you may be expecting is that there are no
5
-- constructors per se; all subclasses share the same constructor method,
6
-- which takes a table of properties that are mixed into the instance.
7
-- e.g. Code like this:
10
-- MyClass = Class:extend{ color = 'red', name = 'robin' }
11
-- myObject = MyClass:new{ color = 'blue' }
14
-- Would set myObject to have a color of 'blue' and a name of 'robin'. There is a
15
-- <onNew> event handler you can use to perform initialization based on these values.
18
-- Called once, when a new object is created via <new()>.
23
-- Creates a subclass of a class object, replacing any class properties
24
-- with those in the object passed. It also sets the subclass's prototype
25
-- property to this class. This alters the passed table in-place.
28
-- obj - table of properties
33
extend = function (self, obj)
35
assert(type(obj) == 'table', 'must extend a table, received a ' .. type(obj))
37
-- copy any table properties into the subclass, so that
38
-- it does not accidentally overwrite them
40
for key, value in pairs(self) do
41
if key ~= '__index' and not obj[key] and type(value) == 'table' then
42
obj[key] = copyTable(self[key])
46
-- __index work to set up inheritance and getters/setters
49
setmetatable(obj, self)
56
-- Extends an object and calls its onNew() handler if it is defined.
57
-- This handler is meant for object-specific initialization,
58
-- not class-wide work.
61
-- obj - table of properties that the new object starts with,
62
-- overriding anything set in the class
67
new = function (self, obj)
68
obj = self:extend(obj)
69
if obj.onNew then obj:onNew() end
74
-- Mixes all properties passed into the current object, overwriting any
75
-- pre-existing values.
78
-- obj - table of properties to mix into the object
83
mixin = function (self, obj)
84
assert(type(obj) == 'table', 'must mix in a table, received a ' .. type(obj))
85
for key, value in pairs(obj) do
90
-- Function: instanceOf
91
-- Checks whether a certain object is anywhere in its inheritance chain.
94
-- class - table to check against
99
instanceOf = function (self, class)
100
local proto = self.prototype
103
if proto == class then
107
proto = proto.prototype