Hello! So the past few days I’ve been working on DataStores and I finally got them working…but my code looks a little bit sloppy from what I’ve seen others do. Does anyone have any tips on how I could improve my DataStore code? Either just better coding practices, or changing how I do some of the code.
Any tips/feedback would be much appreciated!!
local Module = {}
local DataStoreService = game:GetService('DataStoreService')
local DataStore = DataStoreService:GetDataStore("Player_Data_Test22")
local SessionData = {
HighestLevel = {}, -- Format = 124828424_HighestLevel
OtherStat = {} -- Format = 124828424_OtherStat
}
local Defaults = {
HighestLevel = 1,
OtherStat = 10
}
local CanSave = {--[[userID = true]]}
--[[ LOADING STATS WHEN PLAYER JOINS ]]
game.Players.PlayerAdded:connect(function(Player)
local UserId = Player.UserId
local Key = "player-" .. (tostring(UserId))
local PlayerData;
local DataFetchSuccess, ErrorMessage = pcall(function()
PlayerData = DataStore:GetAsync(Key)
end)
if DataFetchSuccess then
print("success")
if PlayerData ~= nil then
print("~= nil")
local StatIndex = 1
for Stat, Value in pairs(SessionData) do
print("indexing")
SessionData[Stat][UserId .. "_" .. Stat] = PlayerData[StatIndex]
StatIndex = StatIndex + 1
end
else
print("== nil")
for Stat, Value in pairs(Defaults) do
print("indexing")
SessionData[Stat][UserId .. "_" .. Stat] = Defaults[Stat]
end
end
else
CanSave[UserId] = false
Player:Kick("Your data failed to load! Please rejoin.")
end
end)
--[[ SAVING STATS WHEN PLAYER LEAVES ]]
game.Players.PlayerRemoving:connect(function(Player)
local UserId = Player.UserId
local Key = "player-" .. (tostring(UserId))
if CanSave[UserId] == false then return end
local ValuesToSave = {}
for Stat, Value in pairs(SessionData) do
table.insert(ValuesToSave,SessionData[Stat][UserId .. "_" .. Stat])
end
local DataSaveSuccess, ErrorMessage = pcall(function()
print("Stats: HighestLevel, OtherStat: " .. game:GetService([[HttpService]]):JSONEncode(ValuesToSave))
DataStore:SetAsync(Key, ValuesToSave)
end)
if not DataSaveSuccess then
local RetryCount = 0
while RetryCount < 4 do
wait(60)
local Success, Error = pcall(function()
DataStore:SetAsync(Key, ValuesToSave)
end)
if Success then
break
end
RetryCount = RetryCount + 1
end
end
--Clearing Stats
CanSave[UserId] = nil
SessionData["HighestLevel"][UserId .. "_HighestLevel"] = nil
SessionData["OtherStat"][UserId .. "_OtherStat"] = nil
end)
return Module