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

Best way to have multiple loops in a script running (at the same time)?

Asked by
LuaQuest 450 Moderation Voter
9 years ago

I'm familiar with 'spawn' and coroutines, but I'm not sure which are the best to use if I'm going to have several loops running at the same time in my code. My script is local, and it's purpose is to animate objects in workspace by simply rotating them to give them a motion effect. Here's my current work:

local sword_1 = workspace:WaitForChild("Sword1")
local sword_2 = workspace:WaitForChild("Sword2")
local sword_3 = workspace:WaitForChild("Sword3")

-- This is my main concern...
spawn(function()
    while wait() do
        sword_1.CFrame = sword_1.CFrame * CFrame.Angles(0,0,0.1)
    end
end)

spawn(function()
    while wait() do
        sword_2.CFrame = sword_2.CFrame * CFrame.Angles(0.1,0,0.1)
    end
end)

spawn(function()
    while wait() do
        sword_3.CFrame = sword_3.CFrame * CFrame.Angles(0,0.1,0)
    end
end)

So basically I'm just wondering if there's a better way to do this. This current method does work, but to me something just looks like it could be improved in both readability, and efficiency. Thanks for reading, hope you can help.

1 answer

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

Rather than using coroutines, condense your code and improve overall efficiency by simply combining all your while loops into a single loop.

local sword_1 = workspace:WaitForChild("Sword1")
local sword_2 = workspace:WaitForChild("Sword2")
local sword_3 = workspace:WaitForChild("Sword3")

while wait() do
    sword_1.CFrame = sword_1.CFrame * CFrame.Angles(0,0,0.1)
    sword_2.CFrame = sword_2.CFrame * CFrame.Angles(0.1,0,0.1)
    sword_3.CFrame = sword_3.CFrame * CFrame.Angles(0,0.1,0)
end
Ad

Answer this question