Sometimes script is not working as expected

Hi, I’m making a random weapon box, sometimes the purchase was successful, but other times it says that the purchase failed, but the player has enough cash so the purchase shouldn’t fail.

Script:

game.ReplicatedStorage.BuyRandomGun.OnServerEvent:Connect(function(player)
local items = game.ReplicatedStorage:FindFirstChild("Guns"):GetChildren()
local randomItem = items[math.random(1, #items)]
local NumberOfTools = #player.StarterGear:GetChildren()
if player.leaderstats.Cash.Value >= 70 and not player.StarterGear:FindFirstChild(randomItem.Name) then
	player.leaderstats.Cash.Value = player.leaderstats.Cash.Value -70
	local klone = randomItem:Clone()
	local klone2 = randomItem:Clone()
	klone.Parent = player.Backpack
	klone2.Parent = player.StarterGear
	game.ReplicatedStorage.SuccessPurchaseBox:FireClient(player)
elseif player.leaderstats.Cash.Value >= 70 and player.StarterGear:FindFirstChild(randomItem.Name) and not NumberOfTools == 6 then
	repeat
	randomItem = items[math.random(1, #items)]
	until not player.StarterGear:FindFirstChild(randomItem.Name)
	player.leaderstats.Cash.Value = player.leaderstats.Cash.Value -70
	local klone = randomItem:Clone()
	local klone2 = randomItem:Clone()
	klone.Parent = player.Backpack
	klone2.Parent = player.StarterGear
	game.ReplicatedStorage.SuccessPurchaseBox:FireClient(player)
else
	game.ReplicatedStorage.FailedPurchaseBox:FireClient(player)
 end
end)

Any error codes we can know? Please provide it.

I have checked and no errors appear.

See what happens if you have less than 70 coins.

It says purchase failed.
But sometimes it also says that even though I have more than 70 coins.

Now try more than 70. Let’s see if it happens again.

Try changing this conditional:

and not NumberOfTools == 6

to this:

and NumberOfTools <= 6

Since you say that sometimes the purchase is failing when you have enough coins, you most likely have something faulty going on with one of your conditions. Try using some print statements in your “FailedPuchaseBox” block to get debugging info.

I solved the issue using brackets in that line.

elseif (player.leaderstats.Cash.Value >= 70) and (player.StarterGear:FindFirstChild(randomItem.Name)) and not (NumberOfTools == 6) then