If you don’t have something to do with UpdateAsync then just stick with SetAsync unless you want to implement session locking. Update async doesn’t mean less data loss etc it’s just a way to mess with data before saving it which means if you just want to save you don’t need update async at all.
The last saved value is retrieved with GetAsync… you use UpdateAsync to check the last value then update it accordingly
1 Like
If you want something that simple, I’d suggest just using SetAsync
. I only recommend using UpdateAsync
for things that depend upon the existing value.
So, something like this:
--!strict
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
local playerPointsDataStore = DataStoreService:GetDataStore("PlayerPointsDataStore-PUT-YOUR-ACTUAL-DATA-STORE-NAME-HERE")
-- this is a map keyed by player and the value is their points
local pointsByPlayer = {}
function generateDataStoreKeyForPlayer(player: Player)
return "player_userId:" .. player.UserId
end
function loadPointsForPlayerAsync(player: Player)
local dataStoreKey = generateDataStoreKeyForPlayer(player)
local dataStoreValue = playerPointsDataStore:GetAsync(dataStoreKey)
if type(dataStoreValue) == "number" then
pointsByPlayer[player] = dataStoreValue
else
pointsByPlayer[player] = 0
end
end
function savePointsForPlayerAsync(player: Player)
if pointsByPlayer[player] == nil then
warn("Cannot save points for player " .. player.Name .. " because their points have not been loaded yet.")
return
end
local dataStoreKey = generateDataStoreKeyForPlayer(player)
playerPointsDataStore:SetAsync(dataStoreKey, pointsByPlayer[player])
end
Players.PlayerAdded:Connect(loadPointsForPlayerAsync)
Players.PlayerRemoving:Connect(function(player: Player)
savePointsForPlayerAsync(player)
pointsByPlayer[player] = nil -- avoid a memory leak
end)
game:BindToClose(function()
for player, pointsForPlayer in pairs(pointsByPlayer) do
savePointsForPlayerAsync(player)
end
end)
This will load on player join, store in a cache (pointsByPlayer
) in Lua, and then save to the data store as you want - including already being wired up to players leaving and the game closing.
2 Likes