PcoWSkbVqDnWTu_dm2ix
We use cookies on this site to enhance your user experience
Collapse Sidebar

UpdateAsync

This function retrieves the value of a key from a data store and updates it with a new value. Since this function validates the data, it should be used in favor of GlobalDataStore/SetAsync|SetAsync() when there’s a chance that more than one server can edit the same data at the same time.

The second parameter is a function which you need to provide. The function takes the key’s old value as input and returns the new value, with these exceptions:

  • If the key does not exist, the old value passed to the function will be nil.
  • If the function returns nil, the update is cancelled.

The value returned by this function is the new value, returned once the altered data is properly saved.

If this function throws an error, the Articles/Datastore Errors|error message will describe the problem. Note that there are also Articles/Datastore Errors|limits that apply to this function.

See the Articles/Data store|Data Stores article for an in-depth guide on data structure, management, error handling, etc.

Parameters

Name Type Default Description

key

The key identifying the entry being retrieved from the data store.

A function which you need to provide. The function takes the key’s old value as input and returns the new value.

Returns

Return Type Summary

The value of the entry in the data store with the given key.


Code Samples


Reward Players for Visiting

The code below awards players 50 points every time they join the game by updating a data store.

local pointsDataStore = game:GetService("DataStoreService"):GetDataStore("Points")
 
game.Players.PlayerAdded:Connect(function(player)
	local playerKey = "Player_" .. player.UserId
	-- Give 50 points to players each time they visit
	local success, err = pcall(function()
		pointsDataStore:UpdateAsync(playerKey, function(oldValue)
			local newValue = oldValue or 0
			newValue = newValue + 50
			return newValue
		end)
	end)
end)