Do Player Objects get cleared from Tables when a player has been Removed

Hey!

Quick question!

If a player is removed from the game (quit), is their Player object removed from Lua tables that I may have them stores in?

For example, I may still need specific data if a player left early, such as their match score:
I am currently saving this in my match state machine within data.Scores and it is stored as [Player: Player] = 0: Number

If a player leaves the game, can I still access this or is it wiped?

It will not automatically get cleared from your table without you explicitly clearing it yourself, unless you set the table up to use weak references.

So, if you have this,

local dataByPlayer = {}

game.Players.PlayerAdded:Connect(function(player)
    dataByPlayer[player] = 0
end)

Then you also should have this to avoid a memory leak (i.e. your table growing infinitely larger as more players infinitely join the server):

game.Players.PlayerRemoving:Connect(function(player)
    dataByPlayer[player] = nil
end)

(or some other cleanup method if you still need to access data after they leave, but you get the idea; you have to clear it yourself)

Until you do that manual cleanup though, the player object will still exist in your table key, even though the player is not in the game. It is destroyed, so it won’t have a parent, but you can still hold a reference to it.

how does it know which “player” to make it nil from the table

The Players.PlayerRemoving event includes in the parameters which player the event is about, just like Players.PlayerAdded does.

https://create.roblox.com/docs/reference/engine/classes/Players#PlayerRemoving

(Notably as of recently, it also passes a second parameter reason you can use to better understand why they are disconnecting https://create.roblox.com/docs/reference/engine/enums/PlayerExitReason, but I did not use/include it in my example)

Perfect! Yep this is what I am currently doing. I am clearing the match data on removal. I think I was having a brain fart thinking about whether player objects automatically got cleared up. Glad they do not. Thanks for the help