What's wrong with my method of saving data?

Script:

local DataStore = game:GetService("DataStoreService"):GetDataStore("Saves")
local saveRemote = game:GetService("ReplicatedStorage"):WaitForChild("Save")

game.Players.PlayerAdded:Connect(function(player)
	local folder = Instance.new("Folder", player)
	folder.Name = "Data"
	
	local ld = Instance.new("Folder", player)
	ld.Name = "leaderstats"
	
	local rebirthCount = Instance.new("IntValue", ld)
	rebirthCount.Name = "Rebirth"

	local damageCount = Instance.new("IntValue", ld)
	damageCount.Name = "Damage"
	
	local plusDamage = Instance.new("IntValue", folder)
	plusDamage.Name = "PlusDamage"
	
	local wins = Instance.new("IntValue", ld)
	wins.Name = "Wins"
	
	local success, errormag = pcall(function()
		local getData = DataStore:GetAsync(player.UserId)
		for i, v in pairs(getData) do
			if i == 1 then
				damageCount.Value = getData[i]
			elseif i == 2 then
				plusDamage.Value = getData[i]
			elseif i == 3 then
				rebirthCount.Value = getData[i]
			elseif i == 4 then
				wins.Value = getData[i]
			end
		end
	end)
	
	if success then
		print("Successfully loaded ".. player.Name.. "'s data!")
	elseif not success then
		-- FIRST TIME JOINING --
		damageCount.Value = 0
		plusDamage.Value = 1
		rebirthCount.Value = 0
		wins.Value = 0
		error("Something went wrong while loading the data of ".. player.Name.. ": ".. errormag)
	end
end)

saveRemote.OnServerEvent:Connect(function(player, val)
	DataStore:SetAsync(player.UserId, val)
	print("Successfully saved ".. player.Name.. "'s data!")
end)

Local Script:

local remote = game:GetService("ReplicatedStorage"):WaitForChild("Save")
local data = game.Players.LocalPlayer:WaitForChild("Data")
local ld = game.Players.LocalPlayer:WaitForChild("leaderstats")
local enabled = false

while true do
	wait(5) -- TIME FOR SAVE
	local saveDataTable = {}
	table.insert(saveDataTable, 1, ld.Damage.Value)
	table.insert(saveDataTable, 2, data.PlusDamage.Value)
	table.insert(saveDataTable, 3, ld.Rebirth.Value)
	table.insert(saveDataTable, 4, ld.Wins.Value)
	remote:FireServer(saveDataTable)
	print("Autosaved ".. game.Players.LocalPlayer.Name.. "'s Data")
end 

Here is my method of saving data, the problem is that in some cases, the data is confused, and for example, wins are swapped with damage. That is, if I saved that the player has 100 damage and 0 victories, then sometimes they change, and at a new entrance to the game, the player has 100 victories and 0 damage. Question why so?

And how do I fix this so that my saves work fine?

You can avoid this by using string keys instead of numbers:

saveDataTable["damage"] = ld.Damage.Value
1 Like

can I please specify the line or place where I should do this?