Adding values to a table sometimes works, sometimes not

I am working on a custom player list. One Server script gets all stats from the datastore and saves them in tables:

-- Data Tables:
local PlayersStats = {
	{name = "Player1", data = {}},
	{name = "Player2", data = {}},
	{name = "Player3", data = {}},
	{name = "Player4", data = {}},
	{name = "Player5", data = {}},
	{name = "Player6", data = {}},
	{name = "Player7", data = {}},
	{name = "Player8", data = {}},
	{name = "Player9", data = {}}
}

If the player joins, I first find an empty table, then add his name and some stats into it. However, sometimes it saves and sometimes it doesn’t. I tried finding a possible bug but I couldnt fix it by myself.

I tried removing parts of the script, changing the way how values are added to the table but nothing worked.

Here is how I add things into the table:

Players.PlayerAdded:Connect(function(player)
	print(PlayersStats[1].data["Name"])
	local emptyTableFound = false
	for i, v in pairs(PlayersStats) do
		if v.data["Name"] == nil then -- empty table found
			print(player.Name.."'s data has been saved under "..v.name)

			minutes = Data_Time:GetAsync(player.UserId)
			if minutes == nil then
				minutes = 0
			end
			wins = Data_Wins:GetAsync(player.UserId)
			if wins == nil then
				wins = 0
			end

			v.data["Name"] = player.Name
			v.data["Time"] = minutes
			v.data["Wins"] = wins

			print(v.data["Name"])

		end
	end
end)

Im testing it with 2 players in roblox studio. This is what it prints:

  12:16:40.330  nil  -  Server - Stats:37
  12:16:40.330  Player1's data has been saved under Player1  -  Server - Stats:41
  12:16:40.814  nil  -  Server - Stats:37
  12:16:40.814  Player2's data has been saved under Player1  -  Server - Stats:41
  12:16:40.814  Player1  -  Server - Stats:57
  12:16:41.138  Player2 

Maybe it is due to the players joining too fast but how can I fix it then?

You probably have a race condition occurring, each time a player is added it will run in a separate thread. I’m not sure how long the getasync calls will take in each case but both threads have probably cleared the if statement without writing to the table, so are overwriting each other (hope that makes sense).

Edit: misread something lol.

It would be more straightforward to have a blank table to which you add the player as the key such as;
Playerstats[player] = {}
Then add the data values to the table.
But perhaps you have different requirements?

1 Like

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