Internationalisation
Bundled Plugins API
lazy
cp.lazy is a middleclass "mix-in" that allows for simple specification of "lazy-loaded" values and functions in class definitions.
Some values and function results in classes are only created once, and may never be created, depending on what happens in the class's lifetime.
In these cases, it is useful to have the value created on demand, rather than when the instance is initialised.
For methods, this can be done like so with standard Lua code:
1
local class = require "middleclass"
2
3
local MyClass = class("MyClass")
4
function MyClass:expensiveThing()
5
if self._expensiveThing == nil then
6
self._expensiveThing = ExpensiveThing()
7
end
8
return self._expensiveThing
9
end
10
11
local myThing = MyClass()
12
local myExpensiveThing = myThing:expensiveThing()
Copied!
For values, it is much trickier, and involves overriding the metatable.__init function. Which is what this mix-in does for you. It allows you to provide a factory function which will be called just once in the object's lifetime, and the result is stored for future calls.
To create a lazy function or method, do the following:
1
local class = require "middleclass"
2
local lazy = require "cp.lazy"
3
4
local MyClass = class("MyClass"):include(lazy)
5
function MyClass.lazy.method:expensiveThing()
6
return ExpensiveThing()
7
end
8
9
local myThing = MyClass()
10
local myExpensiveThing = myThing:expensiveThing()
Copied!
To create a lazy value, it's the same, except applied to the value table:
1
local class = require "middleclass"
2
local lazy = require "cp.lazy"
3
4
local MyClass = class("MyClass"):include(lazy)
5
function MyClass.lazy.value:expensiveThing()
6
return ExpensiveThing()
7
end
8
9
local myThing = MyClass()
10
local myExpensiveThing = myThing.expensiveThing
Copied!
Note that it is a 'method' function, so you can use self to refer to the specific instance that the result will be applied to. The factory function is also passed the key value the result is getting applied to as the next parameter, so you can do something like this:
1
function lookup(instance, key)
2
return instance:expensiveLookup(key)
3
end
4
MyClass.lazy.method.oneThing = lookup
5
MyClass.lazy.method.otherThing = lookup
Copied!
The expensiveLookup function would only get called once for each method, caching the result for future calls.
You can also create cp.prop values:
1
function MyClass.lazy.prop.enabled()
2
return prop.TRUE()
3
end
Copied!
It is very similar to the value factory, but the returned cp.prop will be automatically bound to the new instance and labeled with the key ("enabled" in the example above).

API Overview

API Documentation

Last modified 1mo ago
Export as PDF
Copy link