Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Constantly keep two for loops running within a while loop?

So, I am trying to use two for loops. One iterates through a table, and one is numerical. I want them both to run at the same time, and repeat using a while loop. Here's what I have so far:

spawn(function()
    while char do
        p1, p2 = char.Torso.Position, floater.Position
        local dist = (p1 - p2).magnitude
            for i = 0, math.pi * 100, 0.05 do -- numerical
                weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
                weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
                s.RunService.RenderStepped:wait()
            end
            for i, v in pairs(rainbow) do -- table
                 e.BrickColor = v
            end
    end
end)

How would I do this?

1 answer

✓ Accepted answer

For what you want, you should use coroutines.

Coroutines essentially eradicate any yeilds from the code

There are two ways you could do this.

1) Use coroutine.wrap, which will create a callable thread.

2) User coroutine.create to create a coroutine, then coroutine.resume to run it.

Here's an example of both..

coroutine.wrap;

spawn(function()
	while char do
		p1, p2 = char.Torso.Position, floater.Position
		local dist = (p1 - p2).magnitude
		coroutine.wrap(function()
			for i = 0, math.pi * 100, 0.05 do -- numerical
				weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
				weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
				s.RunService.RenderStepped:wait()
			end
		end)()
		for i, v in pairs(rainbow) do -- table
			e.BrickColor = v
		end
	end
end)

coroutine.resume / coroutine.create

spawn(function()
	while char do
		p1, p2 = char.Torso.Position, floater.Position
		local dist = (p1 - p2).magnitude
		coroutine.resume(coroutine.create(function()
			for i = 0, math.pi * 100, 0.05 do -- numerical
				weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
				weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
				s.RunService.RenderStepped:wait()
			end
		end))
		for i, v in pairs(rainbow) do -- table
			e.BrickColor = v
		end
	end
end)

1 comment

0

Thank you very much! ^w^

This discussion is preserved as it was. New answers, comments, and votes are closed.