Static Methods vs Instance Methods

A static method is a method that belongs to the class itself not to an Instance from that class.

--

An instance method is a method that belongs to an instance from a class, they require an object that gets created to be invoked.

Example:

local Player = {}
local PlayerMethods = {}

local all_players = {}

-- Player.new is a static method
-- It creates an object from Player class
function Player.new(name)
    local player = setmetatable({
        name = name
    }, {
        __index = PlayerMethods
    })
    
    table.insert(all_players, player)
    
    return player
end

-- Player.get_all is a static method
function Player.get_all()
    return all_players
end

-- PlayerMethods:kill is not a static method
-- It requires a player object to be called
function PlayerMethods:kill()
    print("Killed " .. self.name)
end

-- here is an object that we created from Player class
local player = Player.new("Srlion")
player:kill()

-- no object was created to call get_all function
print(#Player.get_all())

Last updated