-
Notifications
You must be signed in to change notification settings - Fork 0
4. Extending a Class
Tom O'Sullivan edited this page Nov 2, 2021
·
1 revision
Having the ability to extend a class gives more potential for code reusability and more. The example below shows how we can extend our Logger class created in the previous page:
local BetterLogger = Class():Extends(Logger) --Starts the definition of a Class and makes it extend Logger.
function BetterLogger:New(class) --Override the default constructor.
self.name = class.__name
end
local getTimestamp = _G.os.time
local formatTimestamp = _G.os.date
local function getTimeString() --"Private" method to get the current time as a string.
return formatTimestamp("%H:%M:%S", getTimestamp())
end
local print = _G.print
function BetterLogger:Log(msg) --A public method to extend the functionality of the superclass' method.
self.__super.Log(self, ("[%s %s] %s"):format(getTimeString(), self.name, msg))
end
return BetterLogger
When extending a class, as seen above, the class being extended gains access to the super class via self.__super
, which allows the original implementation of a method to be called.