hi guys, i made a DataStore and i want to get feedback from more experienced people. is it reliably done or are there unsafe places in my code, if there is an opportunity to give feedback, I will appreciate it.
i may not have done much optimization, but in the future a lot of values will be stored, so i’m contacting you so that i don’t lose the data later and so that it doesn’t get damaged as a result of some bug. >_o
this is my first DataStore, so please don’t judge me too harshly.
-- server module
local navigations = {
acceptPLOT = require("@game/ServerScriptService/server/plot/acceptPLOT"),
rejectPLOT = require("@game/ServerScriptService/server/plot/rejectPLOT"),
data = game:GetService("DataStoreService"),
--..
studio = game:GetService("RunService"):IsStudio(),
isStudio = false -- saved studio
}
local dataPLAYER = {} -- not touch
local data = {}
local default = {
cash = 0,
test = true,
--..
lastJOIN = nil,
lastREJECT = nil
}
local configuration = {
data = "players"
}
function reconcile(...) -- reconcile data
local a = {...} --a[1] - player, a[2] - default data
for key, value in pairs(a[2]) do
if (not a[1][key]) then
a[1][key] = value
end
end
return a[1]
end
function dataPLAYER.load(...) -- load data
local a = {...} -- a[1] - player
local ds = navigations.data:GetDataStore(configuration.data) -- get data
local success, err = pcall(function()
local val = ds:GetAsync(a[1].UserId) or default
if val == nil then
val = table.clone(default)
end
reconcile(val, default)
data[a[1].UserId] = val -- load data
data[a[1].UserId].lastJOIN = os.time() -- save time join
print(val)
end)
if not success then
warn(err)
a[1]:Kick("your data failed to load, please rejoin in game.")
else
print(success)
navigations.acceptPLOT(a[1]) -- load plot player
end
return data[a[1].UserId]
end
function dataPLAYER.save(...) -- save data
local a = {...} -- a[1] - player
local ds = navigations.data:GetDataStore(configuration.data) -- get data
if navigations.isStudio then
return print("studio disabled saved.")
end
local success, err = pcall(function()
local val = data[a[1].UserId]
if val == nil then
val = table.clone(default)
end
ds:UpdateAsync(a[1].UserId, function()
data[a[1].UserId].lastREJECT = os.time() -- save time reject
print(data[a[1].UserId])
return val
end)
end)
if not success then
warn(err)
else
print(success)
end
navigations.rejectPLOT(a[1]) -- reject plot player
return data[a[1].UserId]
end
return dataPLAYER
local navigations = {
dataPLAYER = require("@game/ServerScriptService/server/data/dataPLAYER"),
players = game:GetService("Players")
}
navigations.players.PlayerAdded:Connect(function(player) -- load player data
player.CharacterAdded:Connect(function(character)
navigations.dataPLAYER.load(player)
end)
end)
navigations.players.PlayerRemoving:Connect(function(player) -- save player data
navigations.dataPLAYER.save(player)
end)
game:BindToClose(function() -- save all data
for i, v in navigations.players:GetPlayers() do
navigations.dataPLAYER.save(v)
end
end)