Using while true do in a pairs causes only one to take effect

Hi! I’m making a traffic light system, and I’m doing a for i,v in pairs statement to go through all the lighting sets in the game. It goes something like this.

for i,v in pairs(game.workspace:GetChildren()) do
   if v.Name == 'TrafficLight' then
      while true do
         -- bla bla bla
      end
   end
end

Upon running this, only one traffic light runs through a sequence of green, yellow, and red. The rest remain in it’s neutral state.

I have a feeling this has to do with yielding. I tried putting the while true do system into a function, but that returned the same outcome.

I don’t do this sort of stuff commonly, so I need some assistance from someone who might know better than me. Thanks!

If you wrap the while loop in a coroutine then it won’t yield the for loop

coroutine.wrap(function()
    while true do
        -- bla bla bla
    end
end)()
2 Likes

Oh okay, coroutines are one of the things I’ve never used on Lua! Thanks, I’ll try out your method now!

I’m not sure of this behaviour, but perhaps the infinite loop is only running on the first index? Why do you need a infinite loop anyways? Can’t you just wrap your ipairs loop in a while loop?

Thats a much better way , rather than creating while loops inside of for loop. @afi_arenicepeople , you should wrap your for loop inside the While loop and do the changes for the traffic system , this can avoid coroutine for the moment.