Will this be garbage collected properly?

Hello!

I wrote this bit of code, but I am unsure on whether this will cause a memory leak or not. Is the Destroy method getting rid of everything properly? Is it necessary to add something like self = nil or setmetatable(self, nil)?

Thanks in advance.

local CharacterManager = {}
CharacterManager.__index = CharacterManager

function CharacterManager.new(player)
	local self = setmetatable({}, CharacterManager)
	
	local function update()
		repeat wait() until (player.Character and player.Character.Parent) or not player.Parent
		
		if player.Parent then
			self.character = player.Character
			self.humanoid = player.Character:WaitForChild("Humanoid")
			-- And so forth..
		end
	end
	
	update()
	self.connection = player.CharacterAdded:Connect(update)
	
	return self
end

function CharacterManager:Destroy()
	if self.connection then
		self.connection:Disconnect()
		self.connection = nil
	end
	self.character = nil
	self.humanoid = nil
end

return CharacterManager
3 Likes

You don’t need to set the values of a table you want to collect to nil since it’s a one sided reference.
Metatables get collected when the tables are collected.

I don’t know what you exactly want to achieve with the :Destroy() method, but if you want to remove the CharacterManager entirely, you will have to set it to nil in whatever script you are requiring it in.

1 Like

When an instance is not referenced by anything, it gets gced automatically.