I need some help with looping

Hello, fellow devs
I am new to scripting and have learned some things, but I can’t figure out how to loop a function forever.
I’d rather not spam 1 billion function triggers like this:
looping

Is there a way I can just loop it so it keeps going without doing that?

Thanks, StrangeDev

You can use a while, repeat until, or for loop.

For Loops

While Loops

local toggle = false

while task.wait() do
    if toggle then
        PartOn()
    else
        PartOff()
    end

    toggle = not toggle
end
1 Like

Thanks for replying. So I am looking at the “Loops link” so put While true do at the end after creating the local functions.

Yes, but if you want to have a condition like a if statement

local Number = 12
while Number == 12 do -- loops until Number isnt equal to twelve
wait() -- this so your game doesnt crash

end

If you want the code to run forever, you use while true do, to break a loop, you use break or continue, the code below the loop wont run as the Loop is running, the only way to have it run the code is have it run in the background or break it

I got it to work after some experimentation thanks so much though. I can post a shot of the script if you want me to I made a flashing block I am planning on making a cool sign.

Solution Credit to: xGOA7x

while true do 
   PartOn()
   PartOff()
end

You’ll have to add task.wait() to that, or else it will simply crash your game.

1 Like

This is a bit of a bad solution, if you don’t add a wait(), your script will crash the game!

while true do
   PartOn() -- Fires Code
   wait(1) -- Yields code
   PartOff() -- Fires Off
   wait(1) -- Also Yields code
end

without waiting, the script will constantly fire the code, mutliple times within frames

1 Like

@DasKairo Thanks both I tried it before I saw this and it was working but I am adding it now. Before I already had a wait command at the end of the function but I put it in the While true part just now thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.