I recently asked a question similar to this one but got somewhat unclear answers(In my mind, maybe not yours). So I will now add some more explanation about what confuses me. Here is a script which saves when you leave:
players.PlayerRemoving:Connect(function(plr)--players is: local players = game:GetService("Players")
local plrInfo = serverStorage:FindFirstChild(plr.Name):WaitForChild("PlayerInfo")
if plrInfo.OwnsTycoon.Value then
local tycoonName = plrInfo.OwnedTycoon.Value
local tycoon = game.Workspace.Tycoons:FindFirstChild(tycoonName)
tycoon:Destroy()
local tycoonCopy = savedTycoonsTable[tycoon.Name]:Clone()
local runTycoonDoor = require(moduleScripts.RunTycoonDoor)
runTycoonDoor(tycoonCopy)
tycoonCopy.Parent = game.Workspace.Tycoons
if plr.CanSave.Value then
print("Player can save.")
local specialKey = "User_"..plr.UserId
local moneyToSave = plrInfo.Money.Value
local buildLevelToSave = plrInfo.BuildLevel.Value
local purchasedItemsTable = getTableForDataStore(tycoon, plrInfo)
local mainTableToSave = {moneyToSave, buildLevelToSave, purchasedItemsTable}
local success, message = pcall(function()
mainDataStore:SetAsync(specialKey, mainTableToSave)
end)
if success then
print(plr.Name.."'s data saved successfully")
else
print(plr.Name.."'s data failed to save successfully")
wait(15)
local maxAttemptsAllowed = 3
local saveAttempts = 0
repeat
saveAttempts = saveAttempts + 1
local success, message = pcall(function()
mainDataStore:SetAsync(specialKey, mainTableToSave)
end)
if success then
print(plr.Name.."'s data saved successfully on try "..saveAttempts)
else
print(plr.Name.."'s data failed to save successfully on try "..saveAttempts)
end
wait(10)
until success or saveAttempts == maxAttemptsAllowed
end
end
end
wait()
local plrFolder = serverStorage:FindFirstChild(plr.Name)
plrFolder:Destroy()
end)
local mainGameLoop = require(moduleScripts.MainGameLoop)
mainGameLoop()
In an answer to the previous question incapaz said when quoting the wiki: "Retrieves the value of the key from the website, and updates it with a new value. This function validates the data and must therefore be the standard function to edit data when there is a chance more than one server can edit the same data at the same time.". There is a chance that my script above will update the datastore from two different servers. Especially if I decide to increase the wait between retries. How does UpdateAsync defend from that? The other person who answered my question said: "UpdateAsync is generally considered better because it's a bit faster than SetAsync. It also allows you to look at the old value before you overwrite it with a new one just in case something "doesn't seem right".". How is UpdateAsync faster? Finally, how would it know if something "doesn't seem right"? I am so confused. Help would be much appreciated. Thanks!
