Overwriting value in table doesn't work?

Essentially I have a table which is structured like this :

Stored = {
 [1] = {
  [1] = playeruserid,
  [2] = moreinfo...etcetc
 },

 [2] = {
  [1] = playeruserid,
  [2] = moreinfo...etcetc
 }

}

And as seen in the code below, I’m trying to overwrite if the player id’s data if it already exists.

data[1] = player.UserId
	local ran = false
	for key, dataInfo in pairs (Stored) do
		ran = true
		if tonumber(dataInfo[1]) == tonumber(player.UserId) then -- this if statement passes
			print("match...", Stored[key])
			Stored[key] = nil
			Stored[key] = data -- doesn't overwrite the data, there's many entries being made with the same userid
		else
			table.insert(Stored, data) -- Create new entry
		end
	end
	
	if not ran then
		print("just inserting")
		table.insert(Stored, data) -- Create new entry
	end

Yet somehow I still end up with all these entries:
16198a542ea06cecd9bee2771896add1 (1)

For reference, I’m the only one who’s been testing the game, they are all the same userid

The data is getting overwritten. The reason why you see so many entries is because you’re duplicating the player entry whenever the playerId is not found in your table. Consider removing this line of code:

else
	table.insert(Stored, data) -- Create new entry
end

Also I recommend ordering your data like this:

local stored = {
	playerId = {} -- Data
}

This is much more logical and you do not need to iteratre through the table to find the player’s data. You could simply do local data = stored[playerId] instead which is much more efficient.

1 Like

My data requires me to iterate through each table anyways, but thank you!