I’ve been working with OOP for a bit now but I never really understood how to clean up objects, is just setting self to nil enough to prevent a memory leak?
My code:
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Lobby = {}
Lobby.__index = Lobby
local Replicator = require(ReplicatedStorage.Replicator)
function Lobby.new(type: string)
local self = {}
self.type = type
self.host = nil
self.hostConnection = nil
self.players = {}
if type == "solo" then
self.maxPlayers = 1
elseif type == "duo" then
self.maxPlayers = 2
end
return setmetatable(self, Lobby)
end
function Lobby:AddPlayer(player : Player)
-- Adding a player to the lobby
table.insert(self.players, player.Name)
Replicator.UpdateLobby(self.host, self.players)
end
function Lobby:SetHost(name : string)
self.host = name
self.hostConnection = Players.PlayerRemoving:Connect(function(player)
if player.Name == self.host then
-- Removing the lobby if the host leaves the game
Replicator.RemoveLobby(self.host)
self.hostConnection:Disconnect()
self.hostConnection = nil
self = nil
elseif table.find(self.players, player.Name) then
-- Removing players that are inside the lobby, if they leave the game
table.remove(self.players, table.find(self.players, player.Name))
Replicator.UpdateLobby(self.host, self.players)
end
end)
end
function Lobby:Create()
Replicator.CreateLobby(self)
end
return Lobby