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

Why isn't my onPlayerLeft function saving Cash value?

I am able to get my player Cash value to load. When I spend money in game the leaderstats change how they should. When I leave and re-join, my player's Cash value is back to the starting_cash value. I am also getting an error saying "Argument 2 missing or nil". Can someone give any idea how to make the cash value actually save?

local Players = game:GetService("Players")
local CashDataStore = game:GetService("DataStoreService"):GetDataStore("Cash") 

local STARTING_CASH = 100

local function onPlayerAdded(player)
	local playerKey = "Player_" .. player.UserId
	
	print("User ".. player.UserId.. " Joined")

	local leaderstats = Instance.new("IntValue")
	leaderstats.Name = "leaderstats"

	local Cash = Instance.new("IntValue", leaderstats)
	Cash.Name = "Cash"

	local myCash
	local success, err = pcall(function()
		myCash = CashDataStore:GetAsync(playerKey) or STARTING_CASH
	end)
	if success then
		Cash.Value = myCash
		print("loading "..myCash)
	else
		-- Failed to retrieve data
	end

	leaderstats.Parent = player
end

for _, player in pairs(Players:GetPlayers()) do
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------------------------------------

local function onPlayerLeft(player)
	local playerKey = "Player_"..player.UserId
	
	local savedCash = player.leaderstats.Cash.Value
	savedCash = CashDataStore:UpdateAsync(playerKey)
	print("User "..player.UserId.." disconnected")
	print("User has "..savedCash.." in the bank")	
	
end
Players.PlayerRemoving:Connect(onPlayerLeft)

1 answer

✓ Accepted answer

You are not updating the value in UpdateAsync. It's supposed to have 2 parameter, key and value you want to update.

replace line 44 to:

    savedCash = CashDataStore:UpdateAsync(playerKey, savedCash)

1 comment

0

Yes that solved the issue, but now the load part of that same script is loading the old Cash value. My prints will say how much is in the bank but when I rejoin, the Cash value is the same as when I joined on the previous test. Do you have any idea about that? I'm sorry, I'm pretty new to Lua

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