Code:
local DSS = game:GetService("DataStoreService")
local Config = require(script:WaitForChild("Config"))
local Store = DSS:GetDataStore(Config.KeyName)
local CurrenciesToSave = {}
-- Create default currencies and put them in a table to be cloned
for i, v in pairs(Config.Currencies) do
local new = Instance.new(v.."Value")
new.Name = i
table.insert(CurrenciesToSave, new)
end
-- PlayerAdded function
local function Added(plr)
local PData = Instance.new("IntValue", plr)
PData.Name = "Data" -- Object's children are saved
for _, v in pairs(CurrenciesToSave) do
v:Clone().Parent = PData -- inserts Values into data
end
local Key = "Player_"..plr.UserId -- defines key
local Store = Store:GetAsync(Key) -- gets data
if Store then -- if data exists then overwrite values with data
for i, v2 in pairs(Store) do
PData[i].Value = v2
end
print("Loaded data for "..plr.Name)
else -- if not, then save the data
local TBL = {}
for _, v3 in pairs(PData:GetChildren()) do
TBL[v3.Name] = v3.Value
end
local s, f = pcall(function() -- pcall
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s then
print("Data saved succesfully.")
else -- retry if failed
print("Data saving failed. Retrying.")
local s2, f2 = pcall(function()
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s2 then
print("Retry succesfull.")
else
print("Retry failed.")
end
end
end
end
local function Removing(plr) -- on player remove
local PData = plr.Data -- Player's data
local TBL = {} - table of data to save
for _, v in pairs(PData:GetChildren()) do
TBL[v.Name] = v.Value -- makes values with the Value's name and Value
end
local Key = "Player_"..plr.UserId -- key again
local s, f = pcall(function() -- pcall again
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s then
print("Data Saving Succesfull!")
else -- retry again
print("Data saving failed. Retrying.")
local s2, f2 = pcall(function()
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s2 then
print("Retry succesful")
else
print("Retry failed.")
end
end
end
local function bindtoclose()
for _, plr in pairs(game:GetService("Players"):GetPlayers()) do -- save all player's data
local PData = plr.Data
local TBL = {}
for _, v in pairs(PData:GetChildren()) do
TBL[v.Name] = v.Value
end
local Key = "Player_"..plr.UserId
local s, f = pcall(function()
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s then
print("Data Saving Succesfull!")
else
print("Data saving failed. Retrying.")
local s2, f2 = pcall(function()
Store:UpdateAsync(Key, function()
return TBL
end)
end)
if s2 then
print("Retry succesful")
else
print("Retry failed.")
end
end
end
end
-- connections
game:GetService("Players").PlayerAdded:Connect(Added)
game:GetService("Players").PlayerRemoving:Connect(Removing)
game:BindToClose(bindtoclose)
I’m trying to achieve datastore with less data loss.
Anything I can do to improve?