Looking for clarification regarding variable clean up

I am pretty new and learning as I go… and have been reading that it is very important to ‘clean up’ your variables when you are done with them. (Sorry, I don’t know the vocabulary…)

I am curious if I am understanding this concept correctly.

This little bit of script constantly tracks the player position…

-- track player location
Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local humanoidRootPart = character:WaitForChild("HumanoidRootPart")		
		while humanoidRootPart do
			local xPos = math.round(humanoidRootPart.Position.X / chunkSize, 0)
			local zPos = math.round(humanoidRootPart.Position.Z / chunkSize, 0)
			print(player.Name," is at ",xPos," , ",zPos)
			wait(.25)
		end
	end)
end)

From what I have read, I believe I should be ‘cleaning up’ the xPos and zPos variables? Otherwise all the old coordinate data just piles up in the void as new data is set?

So, would this fix that?..

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local humanoidRootPart = character:WaitForChild("HumanoidRootPart")		
		while humanoidRootPart do
			local xPos = math.round(humanoidRootPart.Position.X / chunkSize, 0)
			local zPos = math.round(humanoidRootPart.Position.Z / chunkSize, 0)
			print(player.Name," is at ",xPos," , ",zPos)
			xPos = nil  -- ADDED THIS
			zPos = nil -- ADDED THIS
			wait(.25)
		end
	end)
end)

Or is this completely unnecessary? Am I understanding this correctly?..

Any advice is appreciated!
Thanks!

There are few circumstances when you actually have to clean up variables! In your case, you do not need to set them to nil. This is because Lua variables are lexically scoped and will be automatically cleaned up once the scope is done. Lua also has a built-in garbage collector, which will clean up data that is no longer in use.

Times when you do need to explicitly clean up memory is when you store it in a table (the exception being weak tables). A common example is if you’re storing information about each player in a game. When the player leaves, you’ll want to set that info to nil somehow. (e.g. if you’re using the player itself as a key in the table.)

3 Likes

I think what you’re doing is re-defining the variable each time instead, just put it above like this:

Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local humanoidRootPart = character:WaitForChild("HumanoidRootPart")	
		local xPos
		local zPos	
		while humanoidRootPart do
			xPos = math.round(humanoidRootPart.Position.X / chunkSize, 0)
			zPos = math.round(humanoidRootPart.Position.Z / chunkSize, 0)
			print(player.Name," is at ",xPos," , ",zPos)
			wait(.25)
		end
	end)
end)

This way you’re just updating the same variable. I’m not an expert and this could be wrong, but from my understanding this is what I think works.

This really clears up my confusion. Thank you!