Am I cleaning up this lobby class properly?

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
2 Likes

Cleaning up objects is quite easy. Essentially all you need to do (alongside setting self to nil) is:

  • Disconnect any existing event connections (connection:Disconnect())
  • Destroy any existing instances (instance:Destroy())
  • If you’re using tweens, make sure to finish them (stopping them with tween:Cancel() or tween:Pause(), or waiting until they’re done with tween.Completed:Wait()) before destroying them (tween:Destroy())

There’s probably one more thing I’m missing but that’s all you need to do to clean up objects.

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.