Run a While Loop inside a For Loop?

Hello! I’m creating for loop that index the gates folder. In this loop includes a while wait() loop which checks the characters distance away from a specific part inside all of the gates inside the gates folder.

for _, gate in ipairs(gates:GetChildren()) do
	
	while wait() do
        -- some code
	end
end

The obvious problem is that since it is a loop, it only indexes the first gates model it comes across. It then runs the loop which does not end, and therefore is stuck on the first gate and does not affect the rest of the gates.

I would like a way for the for loop to continue adding the while loops to all of the gates and preferrably, with a minimal amount of lines to preserve my sanity.

Thank you for reading,
Cafran

Why use a for index loop at all? I would simply improvise your folder, make it one item for checking, and run a while loop that isn’t wrapped in a for index loop on that. Would that work for you?

P.S.

In general, repetitive loops and for index loops do not work together.

You can do that by wrapping the while loop with any of the functions: task.spawn, coroutine.wrap, or spawn.

Here is an example with task.spawn:

for _, gate in ipairs(gates:GetChildren()) do
	task.spawn(function()
        while task.wait() do
            -- some code
        end
    end)
end
1 Like

It’s a simulator portal system, so I need it to index through a continuously growing folder of portals.

It works! Thank you so much. I’ve been trying to wrap my head around this for hours.

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