Skip to content
ldurniat edited this page May 18, 2017 · 3 revisions

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