Methods - cpeosphoros/30log-plus GitHub Wiki
Instances use their class methods.
local maxWidth = 150 -- a maximum width
local maxHeight = 100 -- a maximum height
local Window = class("Window", {width = maxWidth, height = maxHeight})
function Window:init(width,height)
self.width,self.height = width,height
end
-- A method to cap the Window dimensions to maximum values
function Window:cap()
self.width = math.min(self.width, Window.width)
self.height = math.min(self.height, Window.height)
end
local appWindow = Window(200, 200)
appWindow:cap()
print(appWindow.width,appWindow.height) -- outputs 150,100
Methods can also be called within the class constructor. In the previous example, let us use this feature to automatically cap the window instance dimensions upon instantiation.
-- The new class constructor
function Window:init(width,height)
self.width,self.height = width,height
self:cap()
end
-- Previous Window:cap() implementation here
local appWindow = Window(200, 200)
print(appWindow.width,appWindow.height) -- outputs 150,100
Also, bear in mind instances cannot be used to instantiate.
Calling instance:new() or instance() will raise an error.
appWindow = Window:new()
aWindow = appWindow:new() -- Creates an error
aWindow = appWindow() -- Also creates an error
With 30log-plus, classes may implement a special method :setup(...) which
will be called on instantiation, but with self referring to the class object,
not the instance being created, before :init(...) is called on the new
instance.
The parameters of :setup(...) will be the same passed to :new(...).
If a subclass also implements :setup(...), all setup methods will be ran, in
the order they were inherited. In other words, the super class's setup will be
ran before the subclass's.