Breaking a loop

local clickdetector = script.Parent.ClickDetector 
local part = script.Parent
local market = game:GetService("MarketplaceService")

function purchase(player)
    print(player)
    for i, v in pairs (player.Backpack:GetChildren()) do -- loops to find all tools in the player's backpack 
    if v.Name == "Park Ticket" then -- if an item in the player's backpack == "Park Ticket", break the loop
        break -- > doesn't work unfortunately ... can someone tell me why that is?
        end
        market:PromptProductPurchase(player, 986029738)
    end
end
clickdetector.MouseClick:Connect(purchase)

function market.ProcessReceipt (info)
local player = game.Players:GetPlayerByUserId(info.PlayerId)
if info.ProductId == 986029738 then
    game.ServerStorage["Park Ticket"]:Clone().Parent = player.Backpack
    return Enum.ProductPurchaseDecision.PurchaseGranted
end
end

Basically, this is a product script, however, I want it to be run so if the player already has a tool, the prompt will not show up, hence why I added break to the if statement.

The issue I’m having is where I attempted to stop the function, however, I would like to know why it continues to proceed to prompt the product after I’ve used the “break” function.

break -- > doesn't work unfortunately ... can someone tell me why that is?

Additionally, if any of you would suggest on how I could improve this code, that would also be greatly appreciated!

You can use :FindFirstChild() instead of looping through the entire backpack. Also, if the player has the tool equipped, then it will be parented to the character.

Change

to

if player.Backpack:FindFirstChild("Park Ticket") or player.Character:FindFirstChild("Park Ticket") then
     market:PromptProductPurchase(player, 986029738)
end
2 Likes

That’s a very good point, thank you. And thank you for your swift response.

1 Like