How can i connect an infinite loop to an event?

in my game i have an intValue, and when it changes to false, I want to run a while loop until it changes to true, but if i connect the value to a changed event with the while loop in it, how am i supposed to know when to stop the loop when it changes to true?

1 Like

just do

while false do

end

this automatically stops when it’s false
(obviously instead of false do something like intValue.Value == false

1 Like

I don’t quite understand your question, you don’t know how to stop an infinite loop? If so you just need to add a break or return statement.

i think u meant boolValue, and in that case you can do

boolValue.Changed:Connect(function(value)
   if not value then
      while not boolValue.Value do
        ---your code here
      end
   end
end)

this makes it so that it only starts a loop when the value turns false, and ends the loop once it turns true

sort of like this:

local Value = game:GetService("Value")

-- here would be some sort of loop that I need to run when Value changes to false --
-- the loop runs infinetly while Value is false, but stops when it is true again --

ok then i will try this one right now

but the issue with this program is that once the value becomes true once, that while loop will never run again, because you will get to the end of the script, right? In my application, the value changes from true to false throughout the game.

No, a while will start running again if the argument is true, plus, you said you’re using a connection? That way it would run anyhow

thank you @xXSanrioSlayer99 & @theworldis_socruel. It works!

How would you make this true instead of false, I am looking for a script like this for my game but. I would need it to be true instead of it starting when it’s false.

Delete the nots so it checks for true instead of false.


It’s not quite working for me?

there is no delay between turning the light off and turning it back on, so it will be permanantly on. try adding wait(0.5) at the end of your while loop

Oh my! Such a simple thing to add haha.

This now 100% works thank you so much for your help! :grinning: :smiley:

no problem :slight_smile:

its also a good habit to optimize this kind of code with a for loop. since you are going through every light from 1 to 12 you can do this:

while game.ReplicatedStorage.Alarm.Triggered.Value do
    for i=1, 12 do
        script.Parent["Beacon"..i].Lens.SurfaceLight.Enabled = true
    end
    wait(0.5)
    for i=1, 12 do
        script.Parent["Beacon"..i].Lens.SurfaceLight.Enabled = false
    end
    wait(0.5)
end

(your while loop would be replaced with this)

I have updated the script so it’s like this. I will do that from now on!
Thank you for your help… I am off to sleep! I think my brain is a bit fried haha :slightly_smiling_face:

1 Like