How do I pause a loop until a BindableEvent is being fired?

Let’s say this while loop prints 1 to 10. It will stop and wait for the signal from the Bindable Event before it loops again, how’d I achieve that?

while true do
	for i = 1,10,1 do
		print(i)
	end
	
	BindableEvent.Event:Connect(function(data)
		print(data)
	end) -- Will not puase the loop
end

Something similar to :Wait() but I can not include arguments, this is exactly what I want to achieve:

while true do
	for i = 1,10,1 do
		print(i)
	end
	
	BindableEvent.Event:Wait() -- Pause the loop and won't run until this Bindable Event is being fired
	print(data)
end

Have you tried to call event outside of the while loop?
Something like this should be more logical to use:

local flag = false 

BindableEvent.Event:Connect(function(data)
     flag = true
end) 

while true do
	for i = 1,10,1 do
		print(i)
	end
	
	repeat wait() until flag == true

    -- Function from bindable event in which case for it was 'print(data)'
    print(data)

    flag = false
end

RBXScriptConnection:Wait() would be much better for this.

You should avoid doing repeat wait() until X when you can use an event.

2 Likes

you can use a variable

while true do
	for i = 1,10,1 do
		print(i)
	end
	
	local data = BindableEvent.Event:Wait() -- Pause the loop and won't run until this Bindable Event is being fired
	print(data)
end

@ArticGamerTV I don’t think using a flag is efficient especially when repeat wait() is being used, but thanks for the suggestion though.
Never thought of binding it to a variable, thanks!

2 Likes