Datastore Service and Gold for item help

While writing this post I solved half the issue. I feel pretty good about that. haha.

Anyways. I have a script that subtracts gold from my leaderstats before allowing the player to purchase an item.

I need this script to check the players gold before seeing if they have enough gold to make the purchase. It is super late and my brain hurts. Help would greatly be appreciated.

To clarify the item costs 10 gold, If I have 0 gold it gives me -10 gold and still allows purchase of the item. I would like it to not allow the purchase if I dont have the gold.

Here is the script.

local ClickDetector = script.Parent.ClickDetector

local canGiveGun = true

local sound = script.Parent.Buy

ClickDetector.MouseClick:Connect(function(player)

	local backpack = player.Backpack

	local Gun = game.ServerStorage.Equipment["Elf Bow"]

	local gunClone = Gun:Clone()

	for i,v in pairs(backpack:GetChildren()) do

		if v.Name == "Elf Bow" then

			canGiveGun = false

		end

	end

	if canGiveGun then

		gunClone.Parent = backpack
		
		sound:Play()
		
		player.leaderstats.Gold.Value = player.leaderstats.Gold.Value - script.Parent.Gold.Value

	end

	canGiveGun = true


end) 
1 Like

The code that you are showing doesn’t check if the player has enough gold before doing the purchase, you do that before all the code and the new code would look something like this:

local ClickDetector = script.Parent.ClickDetector
local canGiveGun = true
local sound = script.Parent.Buy

ClickDetector.MouseClick:Connect(function(player)
	local backpack = player.Backpack
	local Gun = game.ServerStorage.Equipment["Elf Bow"]

	if player.leaderstats.Gold.Value >= script.Parent.Gold.Value then
		for i,v in pairs(backpack:GetChildren()) do
			if v.Name == "Elf Bow" then
				canGiveGun = false
			end
		end
		if canGiveGun then
			local gunClone = Gun:Clone()
			gunClone.Parent = backpack
			sound:Play()
			player.leaderstats.Gold.Value = player.leaderstats.Gold.Value - script.Parent.Gold.Value
			canGiveGun = true
		end
	end
end) 

You may want to take at look at break and return (Programming in Lua : 4.4) because with them you can skip the canGiveGun bool by simply adding a return to the loop.

1 Like

Thank you for that. It works perfectly.

Do you have any suggestions on how to let players know if they don’t have enough gold? I have been thinking about gui pop up messages.

Or I might just add a hover over message that gives the required amount of gold.

That deppends on your game and likeness but the most common thing is changing the buy button color to red and change the text to “Not enough gold”, wait a second or 2 and return everything back to normal.