Hello! How is it going?
I recently scripted a DataStore2 saving method which works and everything. I just want to know if my code can get any better!
local DataStore2 = require(game:GetService("ServerScriptService").DataStore2)
local CombinedDataStore = DataStore2.Combine("TimeTrials", "TimeTrialsBackup")
local DefaultTable = {
["Under_The_Sea"] = 0,
["Small_World"] = 0,
["Jurassic"] = 0,
["Piggy_Speedway"] = 0,
["Sandy_Secrets"] = 0,
["Space_Heights"] = 0,
["Space_Highway"] = 0,
["Eggsburg"] = 0,
["Tilted_Road"] = 0,
["Space_Turnpike"] = 0,
}
game:GetService("Players").PlayerAdded:Connect(function(Player)
local DataStore = DataStore2("TimeTrials", Player)
local Data
local Success, Error = pcall(function()
Data = DataStore:GetTable(DefaultTable)
end)
if not Success then
error(Error)
end
local TimeTrialsData = Instance.new("BinaryStringValue")
TimeTrialsData.Name = "TimeTrialsData"
TimeTrialsData.Parent = Player
for Map, Value in pairs(Data) do
TimeTrialsData:SetAttribute(Map, Value)
end
for Map, Value in pairs(DefaultTable) do
if not TimeTrialsData:GetAttribute(Map) then
TimeTrialsData:SetAttribute(Map, Value)
end
end
end)
game:GetService("Players").PlayerRemoving:Connect(function(Player)
local DataStore = DataStore2("TimeTrials", Player)
local DataToSave = {}
for Map, Value in pairs(Player.TimeTrialsData:GetAttributes()) do
DataToSave[Map] = Value
end
local Success, Error = pcall(function()
DataStore:Set(DataToSave)
end)
end)
If you have a concern about my code, please let me know. Thanks! WE