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

How to stop a coroutine with a while loop?

Asked by 5 years ago
Edited 5 years ago

coroutine.yield does not seem to stop a coroutine with a while loop inside. For example:

local spam = coroutine.create(function()
    while true do
        print("oof")
        wait(1)
    end
end)

coroutine.resume(spam)
wait(3) --Should print "oof" 3 times
coroutine.yield()

Yet the coroutine will continue to print "oof" indefinitely. Does anybody know of a fix for this?

0
At line 6 you forgot an end) User#19524 175 — 5y
0
Once coroutine.resume is called upon, the loop is started, and can only be stopped with break, so wait(3) will not run. User#22219 20 — 5y

2 answers

Log in to vote
1
Answered by 5 years ago

Don't think you can, while loops cannot be stopped unless break is called upon, what I would do is I would use a function to do the task.

0
What if I needed two loops to run at once? How would I handle that? Perthrosama 24 — 5y
0
I would do a function or a do code block. User#22219 20 — 5y
0
The problem with a function is that it will run until it returns, and I need something that will run in the background while my main code keeps going. Perthrosama 24 — 5y
0
Or a do statement (I don't really know what they're called anyways). User#22219 20 — 5y
View all comments (4 more)
0
I think "do" could run in the background, but I'm not 100% sure. User#22219 20 — 5y
0
You could use also threads such as delay and spawn. User#22219 20 — 5y
0
spawn(function() end) works User#19524 175 — 5y
Ad
Log in to vote
0
Answered by 4 years ago

Use a for loop instead lemme give example:

local f = coroutine.create(function() for i = 1,40 do wait(.05) game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new((math.random(1,3)/10)power,0,0) wait(.05) game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new((-math.random(1,3)/10)power,0,0) end end)

f = coroutine.create(function () while true do wait(.05) game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new((math.random(1,3)/10)power,0,0) wait(.05) game.Players.LocalPlayer.Character.Humanoid.CameraOffset = Vector3.new((-math.random(1,3)/10)power,0,0) end end)

That how I fixed mine when I had that problem

Answer this question