How can I optimize this datastore script?
I am quite new to storing data, but I have read a lot of stuff about it, and I’m still not sure if I should change or add anything. Any help would be appreciated :)
(Also this is my first topic in this category so sorry in advance if there is something wrong )
The code :D
local DSS = game:GetService('DataStoreService')
local playerData = DSS:GetDataStore('playerData')
local cacheModule = require(game.ServerScriptService.CacheModule)
local nosave = {}
-- configs
local errorDeb = 10
local maxStoreRetries = 30
local function retry(plr, str, errorcode)
print('Oops! Failed to ' .. str .. ' data for ' .. plr.Name .. ' [' .. plr.UserId .. ']! Errorcode: ' .. errorcode)
wait(errorDeb)
end
local function cachePlrData(plr, data)
cacheModule[plr.UserId] = data
cacheModule.Updated(plr, data) -- Do event stuff for other scripts
end
local function loadData(plr)
local success, errorcode
local data = cacheModule.default
nosave[plr.UserId] = true
while not success and plr.Parent do
success, errorcode = pcall(function()
data = playerData:GetAsync(plr.UserId)
end)
if plr.Parent then
if success then
if data == nil then -- Set to default value if no data
data = cacheModule.default
end
cacheModule.Merge(plr, data) -- Merges the loaded data if there is any already by adding up the values, so that no data is lost from either
nosave[plr.UserId] = nil
else
if cacheModule[plr.UserId] ~= cacheModule.default then
cachePlrData(plr, cacheModule.default) end
retry('GET', plr, errorcode)
end
end
end
end
local function storeData(plr)
print(cacheModule[plr.UserId] and not nosave[plr.UserId])
if cacheModule[plr.UserId] and not nosave[plr.UserId] then
local success, errorcode
local tries = 1
local data = cacheModule[plr.UserId]
cacheModule[plr.UserId] = nil
while not success and tries <= maxStoreRetries do
success, errorcode = pcall(function()
playerData:SetAsync(plr.UserId, data)
end)
tries = tries + 1
if not success then
retry('STORE', plr, errorcode)
end
end
end
end
game.Players.PlayerAdded:Connect(loadData)
game.Players.PlayerRemoving:Connect(storeData)
The code gets player data when they join, setting their current game data to the default value until it gets the actual progress. If it sets it to the default value it won’t save the default value over. It also stores the data when the player leaves. It does not store the data if it has not been loaded yet in the first place.
I hope to find some suggestions to improve it here to optimize it, since I’m new to data storing.
P.S Is the code readable enough?
Thanks in advance,
Muuun
EDITED to adapt to starmaq’s solution in post 2