DataStoreSystem.rbxl (18.0 KB)
I’ve never handled my DataStores very efficiently in the past, so I’ve attempted a new DataStore system after browsing the DevForum for some solutions. After about an hour, I’ve come up with this system that uses pcall to check for errors in loading the DataStore, and to retry every 60 seconds if it fails.
I’m intentionally saving all data on one key so I can loop through the Data with ease.
I’m unsure if this is an efficient way to handle DataStores, or if there is even a better solution.
(for those of you that don’t want to download the place file, the code is below)
Script
local Players = game:GetService('Players')
local DataStoreService = game:GetService('DataStoreService')
local AlphaDataStore = DataStoreService:GetDataStore('AlphaPlayers')
local KeyVersion = 'Version1'
function Save(Player)
local Data
local Success, Error = pcall(function()
Data = AlphaDataStore:GetAsync(KeyVersion)
end)
if Success then
print('Successfully loaded DataStore')
if Data == nil then -- DataStore is empty, insert a blank table
print('DataStore is empty')
Data = {}
end
for i,v in pairs(Data) do
print(v)
end
for i,v in pairs(Data) do
if Player.UserId == v then
print(Player.Name..' is already saved!')
return true -- Player is already saved here
end
end
-- If we're still running the code at this point, it means the player isn't saved in this DataStore- so get saving!
table.insert(Data, Player.UserId)
AlphaDataStore:SetAsync(KeyVersion, Data)
print('Saved '..Player.Name..' to AlphaPlayers '..KeyVersion..'!')
return true
else
warn('DataStore Error! Error: '..Error) -- DO NOT SAVE! Retry..
return false
end
end
Players.PlayerAdded:Connect(function(Player)
local Saved = Save(Player)
if not Saved then
repeat wait(60) warn('Something while trying to save '..Player.Name..' to AlphaPlayers! Retrying...') Saved = Save(Player) until Saved
end
end)