I thought I was experienced with DataStores, turns out I’m not. I thought I did it the proper way, yet I’m already get these messages which I believe will lead to data loss.
Script:
local dataStoreService = game:GetService("DataStoreService")
local playerService = game:GetService("Players")
local replicatedStorage = game:GetService("ReplicatedStorage")
local serverStorage = game:GetService("ServerStorage")
-- // Main Data Store
local store = dataStoreService:GetDataStore("MainDataStore")
local DEFAULT_DATA = {
taps = 0,
gems = 0,
rebirths = 0,
DataID = 0
}
-- // Functions
local function loadData(client)
local success,data,err
local attempts = 0
while not success do
success,err = pcall(function()
data = store:GetAsync(client.UserId)
end)
if not success then
attempts = attempts + 1
warn("Failed to load " .. client.Name .. "'s data. Attempt #" .. tostring(attempts) .. ". Error: " .. err)
wait(5)
end
end
if data then
client.leaderstats.Taps.Value = data.taps
client.leaderstats.Gems.Value = data.gems
client.leaderstats.Rebirths.Value = data.rebirths
print("Loaded " .. client.Name.. "'s data successfully")
end
end
local function saveData(client,auto)
local success,err
local attempts = 0
while not success do
success,err = pcall(function()
local playerData = store:GetAsync(client.UserId) or DEFAULT_DATA
store:UpdateAsync(client.UserId,function(oldData)
local previousData = oldData or DEFAULT_DATA
if playerData.DataID == previousData.DataID then
playerData.taps = client.leaderstats.Taps.Value
playerData.rebirths = client.leaderstats.Rebirths.Value
playerData.gems = client.leaderstats.Gems.Value
playerData.DataID = playerData.DataID + 1
return playerData
else
return nil
end
end)
end)
if not success then
attempts = attempts + 1
warn("Failed to save " .. client.Name .. "'s data. Attempt #" .. tostring(attempts) .. ". Error: " .. err)
wait(5)
end
end
if success then
print("Saved " .. client.Name.. "'s data successfully")
end
if auto then
end
end
playerService.PlayerAdded:Connect(function(client)
local leaderstats = Instance.new("IntValue")
leaderstats.Name = "leaderstats"
leaderstats.Parent = client
local taps = Instance.new("IntValue")
taps.Name = "Taps"
taps.Parent = leaderstats
local rebirths = Instance.new("IntValue")
rebirths.Name = "Rebirths"
rebirths.Parent = leaderstats
local gems = Instance.new("IntValue")
gems.Name = "Gems"
gems.Parent = leaderstats
loadData(client)
end)
game.Players.PlayerRemoving:Connect(function(client)
saveData(client)
end)
game:BindToClose(function()
for _, client in ipairs(playerService:GetPlayers()) do
coroutine.wrap(saveData)(client)
end
wait(2)
end)
I appreciate help!