Hello,
I just finished testing my new datastore module.
I wanted to know if this is a good method of saving data.
It uses a que system for the saving of data.
Here I made a little flowchart to make it easier to understand what is happening:
To prevent older data from overwriting newer data, it also saves a data version. This shows which data is most recent.
local module = {}
local datastoreserv = game:GetService("DataStoreService")
local datastore = datastoreserv:GetDataStore("PlayerData")
local PlayerDataVersion = {}
local playerleaveconns = {}
local SaveQue = {}
local iterationcode = 0
module.Get = function(Player)
local i = 0
local succes, err
local Data
repeat
succes,err = pcall(function()
Data = datastore:GetAsync(Player.UserId)
end)
if not succes then
warn(err,Player,"trying angin in 5")
wait(2)
end
until i > 3 or succes
if err then
warn(err,Player,"Gave up, Get")
end
if not Data then
Data = {}
Data.Version = 1
end
PlayerDataVersion[Player.UserId] = Data.Version
return Data
end
function SaveQuePos(UserId,Data)
local updatefunc = function(PastData)
if PastData == nil or Data.Version >= PastData.Version then
Data.Version += 1
return Data
else
return nil
end
end
local succes, err = pcall(function()
datastore:UpdateAsync(UserId,updatefunc)
end)
if not succes then
error("DataStore Set faild,", err)
end
end
function IterateQue()
iterationcode = math.random(0,999999)
local curretcode = iterationcode
repeat
if iterationcode ~= curretcode then break end
local spot = SaveQue[1]
local succes, err = pcall(function()
SaveQuePos(spot[1],spot[2])
end)
if not succes then
warn("Save failed",err)
table.remove(SaveQue,1)
table.insert(SaveQue,spot)
else
table.remove(SaveQue,1)
end
wait(2)
until #SaveQue == 0 or iterationcode ~= curretcode
end
module.Set = function(Player,Data)
local UserId = Player.UserId
if typeof(Data) ~= "table" then
error("given data is not a table",Data)
end
if not Player then
error(Player," does not exist")
end
for a,i in ipairs(SaveQue) do
if i[1] == UserId and a ~= 1 then
table.remove(SaveQue,a)
end
end
PlayerDataVersion[UserId] += 1
Data.Version = PlayerDataVersion[UserId]
table.insert(SaveQue,{UserId,Data})
if #SaveQue == 1 then
IterateQue()
end
end
game.Players.PlayerRemoving:Connect(function(Player)
local userid = Player.UserId
wait(10)
PlayerDataVersion[userid] = nil
end)
return module