Data Store script review

Hi this is my first post on the forum. I think this is the right category.

I wanted to update player’s data using UpdateAsync(). I don’t understand much about it but after a few attempts, I got it working some how. Is this the right way?

local dataStore = game:GetService("DataStoreService")
local expStore = dataStore:GetDataStore("Exp")

game.Players.PlayerAdded:Connect(function(player)
	
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = player
	
	local exp = Instance.new("IntValue")
	exp.Name = "Exp"
	exp.Parent = leaderstats
	
	local data
	local success, errorMessage = pcall(function()
		data = expStore:GetAsync(player.UserId.."-exp")
	end)
		
	if success then
		exp.Value = data
	else
		print("Error")
		warn(errorMessage)
	end	
end)

game.Players.PlayerRemoving:Connect(function(player)
	local success, errorMessage = pcall(function()
		expStore:UpdateAsync(player.UserId.."-exp",function(oldData)
			local updatedData = oldData or 0
			updatedData = player.leaderstats.Exp.Value
			return updatedData
		end)
	end)
		
	if success then
		print("Success")
	else
		print("Error")
		warn(errorMessage)
	end		
end)

Thanks!

1 Like

I see a few things.

1) The lines

 local updatedData = oldData or 0
 updatedData = player.leaderstats.Exp.Value

aren’t really needed. You can just return player.leaderstats.Exp.Value in the function you pass to UpdateAsync since you don’t care about the old value.

2) You also won’t want to save the player’s data if you never retrieved their data, if, for example, in the off chance there was a failure in retrieving the data = expStore:GetAsync(player.UserId.."-exp").

if success then
	exp.Value = data
else
	print("Error")
	warn(errorMessage)
    -- somehow mark the data as not needing to be saved.
end

3) And if the call to data = expStore:GetAsync(player.UserId.."-exp") was successful but the data doesn’t exist, data will be nil so you’ll want to check if data is nil and if so, set exp.Value to 0.

Sorry for late reply. Thank you for answering. So base on your feedback:

  1. I can just do
local success, errorMessage = pcall(function()
	expStore:UpdateAsync(player.UserId.."-exp",function(oldData)
		return player.leadrerstats.Exp.Value
	end)
end)

But I care about the old value to lower down the chance of data lossing. How do I do that?

  1. I just have to add an if statement to check whether the data is nil or not?

Again thanks for your feedback.