Hey there,
As the title says, how can I improve this? What I am looking for is:
- Optimization
- Improve readability
Thanks.
local dss = game:GetService("DataStoreService")
local levelDS = dss:GetDataStore("MainData")
local MAX_RETRIES, RETRY_DELAY = 10, 1
local defaults = {
Sticks = 0,
Iron = 0,
Gold = 0,
Coal = 0,
Wood = 0,
Stone = 0,
Relic1 = false,
Relic2 = false,
ClanName = "",
ClanID = "",
ClanRank = "",
Guild = "",
Tooltips = false,
Autojump = false,
Music = 0,
JetskiUnlocked = false,
SpeedboatUnlocked = false,
YachtUnlocked = false
}
local function safeGetAsync(key)
for i = 1, MAX_RETRIES do
local success, data = pcall(function()
return levelDS:GetAsync(key)
end)
if success then
return data or {}
end
task.wait(RETRY_DELAY)
end
return nil
end
local function safeSetAsync(key, data)
for i = 1, MAX_RETRIES do
local success = pcall(function()
levelDS:SetAsync(key, data)
end)
if success then
return true
end
task.wait(RETRY_DELAY)
end
return false
end
local function saveData(player)
local key = "Player_" .. tostring(player.UserId)
local data = {}
for attr, default in pairs(defaults) do
data[attr] = player:GetAttribute(attr)
end
if not safeSetAsync(key, data) then
warn("Critical failure: Could not save data for player " .. player.UserId)
end
end
local function loadData(player)
local key = "Player_" .. tostring(player.UserId)
local data = safeGetAsync(key) or {}
for attr, default in pairs(defaults) do
player:SetAttribute(attr, (data[attr] ~= nil) and data[attr] or default)
end
end
game.Players.PlayerAdded:Connect(function(player)
loadData(player)
player.CharacterAdded:Connect(function()
task.wait(1)
loadData(player)
end)
end)
game.Players.PlayerRemoving:Connect(saveData)
game:BindToClose(function()
for _, player in pairs(game.Players:GetPlayers()) do
saveData(player)
end
end)