Having a question about DataStore

Is this way of saving future proof or can it lead to data loss? And even if the code is ok what can a developer do in case of data loss?

local dataSS = game:GetService("DataStoreService")
local data = dataSS:GetDataStore("Data")

game.Players.PlayerAdded:Connect(function(plr)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = plr
	
	local kills = Instance.new("IntValue")
	kills.Parent = leaderstats
	kills.Name = "Kills"
	kills.Value = 0
	
	local exp = Instance.new("NumberValue")
	exp.Parent = leaderstats
	exp.Name = "EXP"
	exp.Value = 0
	
	--getting the dataStore
	local playerId = "Player_"..plr.UserId
	local saved
	
	local success, errormessage = pcall(function()
		saved = data:GetAsync(playerId)
	end)
	if success and saved then
		kills.Value = saved[1]
		exp.Value = saved[2]
	end
	
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local playerId = "Player_"..plr.UserId
	local savedStats = {}
	local leaderstats = plr:WaitForChild("leaderstats")
	local Kills = leaderstats:WaitForChild("Kills")
	local exp = leaderstats:WaitForChild("EXP")
	table.insert(savedStats, Kills.Value)
	table.insert(savedStats, exp.Value)
	
	local success, errormessage = pcall(function()
		data:SetAsync(playerId, savedStats)
	end)
	
	if success then
		print("data successfully saved")
	else
		warn(errormessage)
	end
end)

1 Like

I don’t see Roblox removing DataStores anytime soon, so yes I would consider it future proof.

There’s not much you can do in the case of data loss unless you wanted to manually edit/restore the data with a DataStore Editor.

One way you could prevent data loss in your script is by binding a function to when the server shuts down.

game:BindToClose(function()
	for _, plr in ipairs(players:GetPlayers()) do
		-- Create A New Thread For Each Player & Save Their Data.
		task.spawn(function()
			local playerId = "Player_"..plr.UserId
			local savedStats = {}
			local leaderstats = plr:WaitForChild("leaderstats")
			local Kills = leaderstats:WaitForChild("Kills")
			local exp = leaderstats:WaitForChild("EXP")
			table.insert(savedStats, Kills.Value)
			table.insert(savedStats, exp.Value)

			local success, errormessage = pcall(function()
				data:SetAsync(playerId, savedStats)
			end)

			if success then
				print("data successfully saved")
			else
				warn(errormessage)
			end
		end)
	end
end)
1 Like

Thanks I really appreciate your help!

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