Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Constantly keep two for loops running within a while loop?

Asked by
aalok 20
10 years ago

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:

01spawn(function()
02    while char do
03        p1, p2 = char.Torso.Position, floater.Position
04        local dist = (p1 - p2).magnitude
05            for i = 0, math.pi * 100, 0.05 do -- numerical
06                weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
07                weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
08                s.RunService.RenderStepped:wait()
09            end
10            for i, v in pairs(rainbow) do -- table
11                 e.BrickColor = v
12            end
13    end
14end)

How would I do this?

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
10 years ago

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;

01spawn(function()
02    while char do
03        p1, p2 = char.Torso.Position, floater.Position
04        local dist = (p1 - p2).magnitude
05        coroutine.wrap(function()
06            for i = 0, math.pi * 100, 0.05 do -- numerical
07                weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
08                weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
09                s.RunService.RenderStepped:wait()
10            end
11        end)()
12        for i, v in pairs(rainbow) do -- table
13            e.BrickColor = v
14        end
15    end
16end)

coroutine.resume / coroutine.create

01spawn(function()
02    while char do
03        p1, p2 = char.Torso.Position, floater.Position
04        local dist = (p1 - p2).magnitude
05        coroutine.resume(coroutine.create(function()
06            for i = 0, math.pi * 100, 0.05 do -- numerical
07                weld.C0 = CFrame.new(3.5 * math.sin(i), math.sin(tick()) * 1.5, 2.5 * math.cos(i))
08                weld.C1 = CFrame.Angles(math.cos(i), math.cos(i), 0)
09                s.RunService.RenderStepped:wait()
10            end
11        end))
12        for i, v in pairs(rainbow) do -- table
13            e.BrickColor = v
14        end
15    end
16end)
0
Thank you very much! ^w^ aalok 20 — 10y
Ad

Answer this question