Hi, I am trying to allow for a function to fully complete before the next iteration in the for loop, there have been some other posts but all outline methods for while loops that dont work the best for for loops.
Here is the code
script.Parent.MouseButton1Click:Connect(function()
if debounce == true then
debounce = false
for i, v in pairs(items) do
print("Looped.")
MarketplaceService:PromptPurchase(player, v)
MarketplaceService.PromptPurchaseFinished:Connect(function(player, assetId, isPurchased)
if isPurchased then
-- Sends receipt
game:GetService("ReplicatedStorage").SendWebhookMessage:FireServer(player.Name, localPlayer.UserId, v, GetProductPrice(v))
-- Removes item from list
script.Parent.Parent.Parent.Items:WaitForChild(v):Destroy()
table.remove(items, v)
print("Purchase complete")
else
print("Purchase failed.")
end
end)
end
debounce = true
end
end)
Here is the output I am receiving 2x Looped indicates the loop has ran twice since there are 2 items in the table - but the for loop has not waited for the function to complete
2x Purchase complete and performs function on both items incorrectly
When you :Connect a function the thread keeps on running.
What you want to do is use PromptPurchaseFinished:Wait() this will yield the thread until the event is called.
That is the cause of the loop running twice. But in this context you will have another problem. PrompPurchaseFinished fires for any player buying something.
It looks like this code is in a Gui, that means it will be replicated to every player. It is typically much better to handle purchases from a single server script that you would put in ServerScriptService.
I don’t really know what you are referring to. When you say “fire”, I think you mean connect.
Each iteration of the loop will connect a function with the current code. The loop will not wait for the event to fire though. It will immediately go through all iterations of the loop in a single heartbeat.