When you use UpdateAsync
, you supply your own function that takes the argument of the player's old value. You return what the new value will be. Setting the Async will completely clear it and replace the saved data with the new one; therefore, your first example is correct. If you used UpdateAsync, it all comes down to what the function is.
SetAsync
1 | local DataStore = game:GetService( "DataStoreService" ):GetDataStore( "Stats" ) |
7 | DataStore:SetAsync( "User_" ..plyr.UserId, { [ "Money" ] = 150 , [ "Life" ] = 75 } ) |
No matter what the previous data was, whether it was an integer, BrickColor or even nil, it is now completely wiped and replaced with the new information.
Here's another way to think of it:
It's like as if you had a variable and you've set it to something else.
3 | variable = "Now I am a string!" |
Now I am a string!
UpdateAsync
With UpdateAsync, it works however you'd like. It takes 2 arguments: the key and then the function used to manipulate that key. The function also has a single argument which is the old value.
3 | DataStore:UpdateAsync( "User_" ..plyr.UserId, function (oldTable) |
4 | oldTable [ "Money" ] = 150 |
Now in this example, the function is editing the table's contents without completely overriding it. Again, the second argument is a function; therefore, UpdateAsync
does whatever you want it do.
Both UpdateAsync and SetAsync can lead to the same result
01 | DataStore:UpdateAsync( "User_" ..plyr.UserId, function (oldTable) |
03 | oldTable [ "Money" ] = 150 |
07 | return { [ "Mana" ] = 50 } |
12 | local oldTable = DataStore:GetAsync( "User_" ..plyr.UserId) or { [ "Mana" ] = 50 } |
13 | oldTable [ "Money" ] = 150 |
15 | DataStore:SetAsync( "User_" ..plyr.UserId, oldTable) |
Both result in the same outcome.
Conclusion
So, both can do the same depending on how you code. Neat. Is there situations where you use one over the other? UpdateAsync
is great, but the function that you put inside of it cannot yield at all. For example, you cannot use wait
. You can use SetAsync
in situations where you'd want a yield for whatever reason. UpdateAsync
is great for functions where the previous value is important. For example, a function that adds 50 money every minute in the game. UpdateAsync
is also better for situations where you have code that is using GetAsync
and then using that information almost immediately afterwards to SetAsync
. Use UpdateAsync
in this case as you already get the old value by default as a variable with this function, and GetAsync
can sometimes return cached or old data. If another script is changing the same DataStore with the same key, you might also want to use UpdateAsync
to avoid situations where a player gets money in game, but you save money data from 30 seconds ago.
IncrementAsync
is also great for a money system like this, you should look into it! It's not useful in this case, however, where the data is a table and not a number like an integer.
Hope it helps! -LordDragonZord