Hey! Can you please check my code if this is a safe dataStore? It works fine but I want to avoid Data-Loses as much as possible. Thanks.
players.PlayerRemoving:Connect(function(plr)
--Save his data
local success, errormessage = pcall(function()
local leaderstats = plr:WaitForChild("leaderstats")
local tableToSave = {leaderstats:WaitForChild("Coins").Value, leaderstats:WaitForChild("Gems").Value, leaderstats:WaitForChild("Gifts").Value}
StatsDataStore:SetAsync(plr.UserId, tableToSave)
end)
if errormessage then --Try again
print(errormessage)
local leaderstats = plr:WaitForChild("leaderstats")
local tableToSave = {leaderstats:WaitForChild("Coins").Value, leaderstats:WaitForChild("Gems").Value, leaderstats:WaitForChild("Gifts").Value}
StatsDataStore:SetAsync(plr.UserId, tableToSave)
end
end)
game:BindToClose(function()
for i,v in next, players:GetPlayers() do
local success, errormessage = pcall(function()
local leaderstats = v:WaitForChild("leaderstats")
local tableToSave = {leaderstats:WaitForChild("Coins").Value, leaderstats:WaitForChild("Gems").Value, leaderstats:WaitForChild("Gifts").Value}
StatsDataStore:SetAsync(v.UserId, tableToSave)
end)
if errormessage then
local leaderstats = v:WaitForChild("leaderstats")
local tableToSave = {leaderstats:WaitForChild("Coins").Value, leaderstats:WaitForChild("Gems").Value, leaderstats:WaitForChild("Gifts").Value}
StatsDataStore:SetAsync(v.UserId, tableToSave)
end
end
end)
Anything I should improve? I thought about a loop that goes something like this;
while errormessage do
save
end
But idk if that’s a good idea.
Thanks!
Edit: I know, I could use DS2 but I don’t really want to, just tell me if this is safe please.
Try and save every minute, and kick out the player from the game if the data does not load, or prevent them from purchasing the items if the data does not load. BUT ALWAYS CHECK IF THE PLAYERS DATA IS LOADED BEFORE SAVING.
The way I would do it is by inserting a Boolean value into a player, called dataLoaded which will be set to false by default, and set it to true if the data loads without an error message, and have a server script which runs every 60 seconds, with a for loop thru every player. And have it check if the Boolean value is true.
Edit: fixed bad wording