This is my stats module that handles and save stats. It works fine and has customizable settings. I am wondering what I should do to improve this. Thanks
local StatsManager = {}
local Settings = {}
Settings.TriesAllowed = 3
Settings.DataKey = "BetaKey"
Settings.StudioSave = false
Settings.DefaultTable = {Cash = 0}
local MainStore = game:GetService("DataStoreService"):GetDataStore(Settings.DataKey)
local StatReplicator = require(script.Parent.StatReplicator)
function StatsManager:SetupPlayerData(player)
local data
local tries = 0
local success
repeat
tries = tries + 1
success = pcall(function()
data = MainStore:GetAsync(player.UserId)
end)
if not success then wait(1) end
until tries == 3 or success
if not success then
warn("error loading data for "..player.Name)
return
end
if data then
StatsManager[player.UserId] = data
else
StatsManager[player.UserId] = Settings.DefaultTable
end
end
function StatsManager:IncrementStat(player, statName, incrementValue)
if StatsManager[player.UserId][statName] ~= nil then
StatsManager[player.UserId][statName] = StatsManager[player.UserId][statName] + incrementValue
else
warn(statName.." does not exist for "..player.Name)
end
end
function StatsManager:SetStat(player, statName, newValue)
if StatsManager[player.UserId][statName] ~= nil then
StatsManager[player.UserId][statName] = newValue
else
warn(statName.." does not exist for "..player.Name)
end
end
function StatsManager:SaveStats(player)
local tries = 0
local success
repeat
tries = tries + 1
success = pcall(function()
MainStore:SetAsync(player.UserId, StatsManager[player.UserId])
end)
if not success then wait(1) end
until tries == 3 or success
if not success then
warn("error saving data")
end
end
function StatsManager:GetStat(player, statName)
if StatsManager[player.UserId][statName] ~= nil then
return StatsManager[player.UserId][statName]
else
warn(statName.." does not exist for "..player.Name)
end
end
game.Players.PlayerRemoving:Connect(function(player)
if not Settings.StudioSave then return end
StatsManager:SaveStats(player)
end)
game:BindToClose(function()
if game:GetService("RunService"):IsStudio() == false then
for _,player in ipairs(game.Players:GetPlayers()) do
wait(1)
StatsManager:SaveStats(player)
end
else
if not Settings.StudioSave then return end
wait(2)
end
end)
return StatsManager