Datastore Glitch?

Hey guys, I have made a data store to save cash. Seems to act weird, sometimes saves, sometimes doesn’t here it is:

Script is located in the workspace

local DataStore = game:GetService(“DataStoreService”):GetDataStore(“StoreName”)

game.Players.PlayerAdded:connect(function(player)
local key = “key-”…player.userId
local folder = Instance.new(“Folder”,player)
folder.Name = “leaderstats”
local cash = Instance.new(“IntValue”,folder)
cash.Name = “Cash”

 local save = DataStore:GetAsync(key)
 if save then
	cash.Value = save[1]
else
	local cashload = {cash.Value}
	DataStore:SetAsync(key,cashload)
end

end)

game.Players.PlayerRemoving:connect(function(player)
local key = “key-”…player.userId
local load = {player.leaderstats:FindFirstChild(“Cash”).Value}
DataStore:SetAsync(key,load)
end)

(Sorry I don’t know how to paste it properly.)

sometimes, the game closes before datastore finishes its task, and when it’s saving something, the player already does not exist. You can fix this easily by adding this at the end of your script:

game:BindToClose(function()
wait(5)
end)

This will wait 5 seconds before making the server (client) shut down.

for more documentation, click here.

Use a pcall for the SetAsync to ensure that you know when it fails to save

Can you show me an example? I am a little confused.

for example, instead of simply using

DataStore:SetAsync(key,cashload)

you do

local success, errorMsg = pcall(function()
DataStore:SetAsync(key,cashload)
end)

if success then
print("Saved")
else
print("error: ")
error(errorMsg)

this is a protected call.

for more documentation, click here.