Why is this loop repeating infinitely?

:expressionless: Yes, the second scripting support of mine today…
I’m trying to make a meter that counts up than empties, but then it just starts over and counts up infinitely. The Break works, but the loop itself doesn’t stop.
I have 2 scripts connected with BindableEvents, I’ll provide both:

Scripts
To detect clicking:
local clickDetector = script.Parent.ClickDetector

local clicked = script.Parent.Parent.Clicked

local isFinished = script.Parent.Parent.Finished

local alreadyClicked = false

function onMouseClick()

if not alreadyClicked then

alreadyClicked = true

-- makes another click not fire the event again

clicked:Fire()

print("Event fired...")

end

end

local function finished()

alreadyClicked = true

print("Event opened!")

--re-opens the event

end

clickDetector.MouseClick:Connect(onMouseClick)

isFinished.Event:Connect(finished)
To run the loop:
local meter = script.Parent
local Clicked = script.Parent.Parent.Parent.Parent.Clicked
local running = false
local Finished = script.Parent.Parent.Parent.Parent.Clicked
local size = meter.Size

local function OnClicked()
	if not running then
		running = true
		for i = 1, 10 do
			meter.Size = UDim2.new(i / 10,size.X.Offset,size.Y.Scale,size.Y.Offset)
			wait(1)
			if meter.Size.X.Scale == 1 then
				print("Condition activated, attempting to break loop...")
				break
			end
		end
		running = false
		Finished:Fire()
		print("Loop ended; attempting to open event...")
	end
end
Clicked.Event:Connect(OnClicked)
Explorer Path

(Ignore the body object)
Screen Shot 2020-09-16 at 6.41.37 PM

@vlopste Hey
Are there any errors in the output?

For - do can’t use break to stop

yes, you can use break to stop a for loop…

2 Likes

I don’t see what would be wrong with this, but I believe in your finished() function you meant to set alreadyClicked to false.

1 Like

The reason that it keeps looping is because you have selected the wrong bindable event for Finished . This means that when the loop has finished it will raise the clicked event and run the loop again.

local Finished = script.Parent.Parent.Parent.Parent.Clicked
  • Remove this and change this to your Finished event
3 Likes

Sorry for the late response, but strangely enough, both the solutions didn’t work.
@KhaosDev, Thanks! I didn’t notice that :sweat_smile:
@55167233gf, No errors, strangely.
@jediritz, Yes, I’m trying to get the loop to stop.

Is there another command that can stop the loop, or is it just break ?

What FeudalDeity said should solve the problem. If not, then try removing the Finished:Fire call and see if if still repeats.

It still repeats. I’m thinking it’s something with the for 1, 10 loop, not recursions.

Strange, maybe try for i = 1, 10, 1? I doubt that would make a difference but it’s worth a try lol

It wasn’t the increment; I was testing it on the wrong model! :sweat_smile:
I should delete the other packages before posing on scripting support…

1 Like