Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How does UpdateAsync work and is it better for trade system?

I was wondering if i were to make a trade system do i either have to UpdateAsync or SetAsync to the players datastore?

1 answer

✓ Accepted answer

Well, this is sort of a broad question, and I don't know what kind of stuff your trading or whatever, but first you are going to need to know the differences betweenSetAsync() and UpdateAsync().

SetAsync()sets the value of a key, and overwrites any data existing in that key.

The ROBLOX wiki states multiple times that SetAsync() is dangerous because

If the previous value of the key is important, use UpdateAsync. Using GetAsync to retrieve a value and then setting the key with SetAsync is dangerous because GetAsync sometimes returns cached data, and other game servers may have modified the key. Mind that there are limits that apply to this.

And they recommend using UpdateAsync() instead. So in the case that you will have multiple servers setting the value of the key, then it really is important to use UpdateAsync().

If I recall correctly, the best way is to use SetAsync() to create keys, and then UpdateAsync() to modify the keys.

Code Examples:

SetAsync():

local DataStore = game:GetService("DataStoreService"):GetDataStore("PlayerVisits")
 
game.Players.PlayerAdded:connect(function(Player)
    local PlayerKey = "user_" .. Player.userId
    DataStore:SetAsync(PlayerKey, 0)
end)

UpdateAsync():

local DataStore = game:GetService("DataStoreService"):GetDataStore("Points")
 
game.Players.PlayerAdded:connect(function(player)
	local key = "user_" .. player.userId
	--we want to give 50 points to users each time they visit
	DataStore:UpdateAsync(key, function(oldValue)
		local newValue = oldValue or 0 --oldValue might be nil
		newValue = newValue + 50
		return newValue
	end)
end)

Hope this helps

Sources:

http://wiki.roblox.com/index.php?title=API:Class/GlobalDataStore/SetAsync

http://wiki.roblox.com/index.php?title=API:Class/GlobalDataStore/UpdateAsync

This discussion is preserved as it was. New answers, comments, and votes are closed.