Internationalisation
Bundled Plugins API
delegator
cp.delegator is a middleclass "mix-in" that allows for simple specification of "delegated" values and functions in class definitions.
This allows you to compose an object from other objects, but allow methods or values from the composed values to be accessed directly via the composing parent object.
For example:
1
local class = require "middleclass"
2
local delegator = require "cp.delegator"
3
4
local Minion = class("Minion")
5
6
function Minion:doTask()
7
-- does something...
8
return true
9
end
10
11
local Boss = class("Boss"):include(delegator):delegateTo("minion")
12
13
function Boss:initialize()
14
end
15
16
function Boss:hireMinion(minion)
17
self.minion = minion
18
end
19
20
local johnSmith = Boss()
21
local joeBloggs = Minion()
22
23
johnSmith:doTask() -- error: no 'doTask' method available.
24
25
johnSmith:hireMinion(minion)
26
johnSmith:doTask() -- can now do the task, because his minion does it for him.
27
johnSmith.minion:doTask() -- The exact same thing.
Copied!
The order that delegator is included with other mixins can affect how it functions. For example, when mixing with cp.lazy, if cp.lazy is mixed in second, like so:
1
local MyClass = class("MyClass"):include(delegator):include(lazy):delegateTo("delegate")
2
3
function MyClass:initialize()
4
self.delegate = {
5
value = "delegated value"
6
}
7
end
8
9
function MyClass.lazy.value()
10
return "lazy value"
11
end
12
13
local myInstance = MyClass()
14
assert(myInstance.value == "delegated value") -- passes
15
assert(myInstance.delegated.value == "delegated value") -- passes
Copied!
...then any delegated methods will take priority over lazy ones. Most likely you want to put lazy first, like so:
1
local MyClass = class("MyClass"):include(lazy):include(delegator):delegateTo("delegate")
2
3
function MyClass:initialize()
4
self.delegate = {
5
value = "delegated value"
6
}
7
end
8
9
function MyClass.lazy.value()
10
return "lazy value"
11
end
12
13
local myInstance = MyClass()
14
assert(myInstance.value == "lazy value") -- passes
15
assert(myInstance.delegated.value == "delegated value") -- passes
Copied!
The easy way to remember is to read them together - "lazy delegator" sounds better than "delegator lazy".

API Overview

API Documentation

Last modified 1mo ago
Export as PDF
Copy link