How would I fix this datastore script?

I am working on a game that has a currency in it. I am trying to make it so that the currency saves when the player leaves the server. My script won’t work, and the “cash” on lines 21 and 24 are underlined in red. I tried putting a local cash at the top of the script but it did nothing. Here is the script:

local dataStores = game:GetService("DataStoreService"):GetDataStore("CoinnDataStore")
local defaultCash = 0
local playersLeft = 0
game.Players.PlayerAdded:Connect(function(player)
	playersLeft = playersLeft + 1
	local stats = Instance.new("BoolValue",player)
	stats.Name = "leaderstats"
	
	local cash = Instance.new("IntValue",stats)
	cash.Name = "Coinn"
	cash.Value = 0
end)
-- Data Stores --
local player_data
pcall(function(player)
	player_data = dataStores:GetAsync(player.UserId.."-Coinn")
end)

if player_data ~= nil then
	--player has saved data, load it in
	cash.Value = player_data
else
	-- New Player
	cash.Value = defaultCash
end

local bindableEvent = Instance.new("BindableEvent")

game.Players.PlayerRemoving:Connect(function(player)
	pcall(function()
		dataStores:SetAsync(player.UserId.."-Coinn", player.leaderstats.Coinn.Value)
		print("Player Data Saved")
		playersLeft = playersLeft - 1
		bindableEvent:Fire()
	end)
end)

game:BindToClose(function()
	--triggered on shutdown
	while playersLeft > 0 do
		bindableEvent.Event:Wait()
	end
end)

Please help!

First of all, based on your script, you might want to make it so your GetAsync will be INSIDE the PlayerAdded scope, that’s why the “cash” is underlined. Because there’s no cash variable anywhere inside the current scope.

Also, for your pcall; what are you trying to achieve?

pcall(function(player) -- not sure what are you trying to do here.
	player_data = dataStores:GetAsync(player.UserId.."-Coinn")
end)

If you’re trying to make a success/error, it should be written this way;

local success, response = pcall(function()
    player_data = dataStores:GetAsync(player.UserId.."-Coinn")
end)
game.Players.PlayerAdded:Connect(function(player)
	playersLeft = playersLeft + 1
	local stats = Instance.new("BoolValue",player)
	stats.Name = "leaderstats"
	
	local cash = Instance.new("IntValue",stats)
	cash.Name = "Coinn"
	cash.Value = 0

local player_data
local success, response = pcall(function()
    player_data = dataStores:GetAsync(player.UserId.."-Coinn")
end)

if player_data ~= nil then
	--player has saved data, load it in
	cash.Value = player_data
else
	-- New Player
	cash.Value = defaultCash
end
end)
1 Like

I got most of the script from a YouTube tutorial, but I modified it a bit. I didn’t modify the pcall though. That was straight from the tutorial.

Script works now, and it saves! Thank you so much!