DataStore2, how to update a table?

I’m trying to update the saved table with the new table. It works perfectly using :Set() but I want to use Update() because it’s better and more fail proof.

The code looks like this:

local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserSaveIndex = require(ReplicatedStorage.UserSaveIndex)
local ServerScriptsService = game:GetService("ServerScriptService")
local DataStore2 = require(ServerScriptsService.DataStore2)

local ONE_THOUSAND_MONEY = 868744642
local FIVE_THOUSAND_MONEY = 868794186
local TEN_THOUSAND_MONEY = 868801246

MarketplaceService.ProcessReceipt = function(receipt)
-- Receipt has PurchaseId, PlayerId, ProductId, CurrencySpentValue, CurrencyType, 
PlaceIdWherePurchased
local ID = "receipt-" .. receipt.PurchaseId
local receiptStore = DataStore2(ID, game.Players:GetPlayerByUserId(receipt.PlayerId))

local success = nil

pcall(function()
	success = receiptStore:Get()
end)

-- If it has already been bought (purchase ID generated every purchase, unique)
if success then
	return Enum.ProductPurchaseDecision.PurchaseGranted
end

local player = game.Players:GetPlayerByUserId(receipt.PlayerId)

-- If the player has left the game or disconnected during the purchase proccess
if not player then
	return Enum.ProductPurchaseDecision.NotProcessedYet -- Give the purchase next time they join/next time fired
else
	local moneyStore = DataStore2("money", player)
	local saveIndex = UserSaveIndex.getUserSaveNumber(player)
	local userMoney = moneyStore:Get()
	
	if receipt.ProductId == ONE_THOUSAND_MONEY then
		userMoney[saveIndex] = userMoney[saveIndex] + 1000
	end
	
	if receipt.ProductId == FIVE_THOUSAND_MONEY then
		userMoney[saveIndex] = userMoney[saveIndex] + 5000
	end
	
	if receipt.ProductId == TEN_THOUSAND_MONEY then
		userMoney[saveIndex] = userMoney[saveIndex] + 10000
	end
	moneyStore:Update(userMoney)
	
	pcall(function()
		receiptStore:Update(true)
	end)
	
	return Enum.ProductPurchaseDecision.PurchaseGranted
end
end

The error message I’m getting is " 12:04:54.439 - ServerScriptService.DataStore2:235: attempt to call local ‘updateFunc’ (a table value)"

1 Like

I’d say to just stick using :Set() because it doesn’t really matter in DataStore2. See the picture from the documentation.

1 Like

It really depends how you would organize this. dataStore:Get() — requires a value in case there is nothing to “Get”.

dataStore:Update() is a value that requires a “return” value.

dataStore:Update(function(oldValue)
     local newValue = oldValue
     if newValue ~= nil then
          return newValue
     end
end)
1 Like