I want know all the inefficiencies in this code, so I can make this script better.
DATASTORE SCRIPT:
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local PointsDataStore = DataStoreService:GetDataStore("PointsDataStore")
local autosaveInterval = math.random(240, 360)
Players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local points = Instance.new("IntValue")
points.Name = "Points"
points.Parent = leaderstats
local data
local success, err = pcall(function()
data = PointsDataStore:GetAsync(player.UserId.."-points")
end)
if success then
if data and data ~= 0 then
print("Data loaded successfully!")
player:WaitForChild("leaderstats"):WaitForChild("Points").Value = data
else
print("New player! Creating data...")
player:WaitForChild("leaderstats"):WaitForChild("Points").Value = 0
end
else
warn("There was an error whilst loading data!")
warn("Error code: "..err)
end
spawn(function()
while true do
wait(autosaveInterval)
print(points.Value)
local success, err = pcall(function()
PointsDataStore:SetAsync(player.UserId.."-points", points.Value)
end)
if success then
print("Autosave complete!")
else
warn("Unable to save data!")
warn("Error code: "..err)
end
end
end)
end)
Players.PlayerRemoving:Connect(function(player)
local points = player:WaitForChild("leaderstats"):WaitForChild("Points")
local tries = 0
local success, err
repeat
tries = tries + 1
success, err = pcall(function()
PointsDataStore:SetAsync(player.UserId.."-points", points.Value)
end)
print("Tries..: "..tries)
if not success then wait(1) end
until success or tries == 3
if success then
print("Data saved succesfully!")
else
warn("There was an error whilst saving data!")
warn("Error code: "..err)
end
end)
game:BindToClose(function()
for _, player in pairs(Players:GetPlayers()) do
DataStoreService:SetAsync(player.UserId.."-points", player:WaitForChild("leaderstats"):WaitForChild("Points").Value)
end
end)
(I’m not too experienced with DataStores which is why I’m asking for help.)
EDIT: Looking around it seems SetAsync() is pretty destructive and it’s much better to use UpdateAsync(), however I don’t know how to use UpdateAsync() so I’ll need some help there.
EDIT2: Just experienced this warning, I hope there can be a way to prevent it.
DataStore request was added to queue. If request queue fills, further requests will be dropped. Try sending fewer requests.Key = 277320496-points