local DataGold = DataStore2("Gold", player)
DataGold:Set(player.Stats.Gold.Value)
I advise you to change the value of direct storage in datastore2 data: Increment (1.0) “1” is the value you want to add (if you want you can subtract “-1”) and “0” is the value initial.
if you feel better, try it this way: (not tested if it works)
I’m saving all items a player owns in a table. Every time he buys something a RemoteFunction is fired that checks whether the player has enough coins and if so inserts the item into the table:
local function CheckSale(Player,Item,Category)
local Price = ShopItems[Category][Item].Price.Value
local CoinsData = DataStore2("Coins",Player)
local PlayerItemsData = DataStore2("PlayerItems",Player)
local PlayerItems = PlayerItemsData:Get()
if CoinsData:Get() >= Price and not PlayerItems[Item] then
CoinsData:Increment(-Price) -- subtract price
table.insert(PlayerItems,Item) -- add item to table
PlayerItemsData:Set(PlayerItems) -- save new table
return true -- purchase successful
else
return false -- purchase failed
end
end
CheckSaleRemote.OnServerInvoke = CheckSale
My shortened leaderstats script:
local PlayerItemsData = DataStore2("PlayerItems",Player)
local function UpdatePlayerItems(UpdatedValue)
PlayerItemsData:Set(UpdatedValue)
end
UpdatePlayerItems({})
PlayerItemsData:OnUpdate(UpdatePlayerItems)
I’m starting to use DataStore2, and because everything of here is new for me, how do i save a dictionary? Of course i have searched for threads in this forum, but they were not helpful, thanks for reading.
There isn’t a need to–they don’t contain any information other than “you can save tables”. Literally just call :Set and :Save like you would any other value. Tables are not different than any other data in terms of saving.
local defaultTable = {["Points"] = 0}
local mytable = myTableDatastore:GetTable(defaultTable) --get the table
mytable["Points"] = mytable["Points"] + 1 --edit the table
myTableDatastore:Set(mytable) --set the table (same way as saving an Intvalue)
I have a question regarding DataStore:OnUpdate. If I register a callback, it’s called every time the cache is updated. Suppose I make two updates in the cache in quick succession (e.g. I have a table in cache and its values are updated by different scripts. At some point two keys are updated almost at the same time in different scripts). In this scenario, OnUpdate has the guarantee that the first update will finish before the second one starts?
That’s true. I was confused for a moment because each script runs in its own thread and I wondered if the thread scheduler could switch threads in the middle of the execution of one of the scripts. That’s not the case as explained here (Promises and Why You Should Use Them). Since each update runs until completion or until it yields there is no worries that onUpdate will run over the other.
Thank you for your answer.