-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.lua
59 lines (44 loc) · 1.4 KB
/
object.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- some notes:
-- Component functions are Hookified
-- 'add' is reserved as a function name, for adding Components to the Object
-- Object doesn't call init() for Components, you have to do that once they are all added
-- private functions should be local to the Component's module, as there is no way to make a member function private to the Component
local Hook = require('hook')
local C = Class()
-- components are just tables with functions in them, with a metatable for type checking
local ComponentMT = {}
function C.Component()
return setmetatable({}, ComponentMT)
end
local function isComponent(c)
return getmetatable(c) == ComponentMT
end
function C:init()
self.hooks = {}
self.warned = {}
end
function C:add(comp)
assert(isComponent(comp), 'argument must be an Object.Component')
for name, value in pairs(comp) do
if type(value) == 'function' then
if not self.hooks[name] then
self.hooks[name] = Hook(name)
end
self.hooks[name]:register(value)
else
error('Component with non-function value: '..name)
end
end
end
function C:call(name, ...)
local hook = self.hooks[name]
if not hook then
if not self.warned[name] then
print('Warning: hook called with no registered functions: ' .. name)
self.warned[name] = true
end
return
end
return hook(self, ...)
end
return C