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
9 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:

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

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
9 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;

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)
0
Thank you very much! ^w^ aalok 20 — 9y
Ad

Answer this question