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

How to stop a coroutine with a while loop?

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?

2 comments

0

At line 6 you forgot an end)

0

Once coroutine.resume is called upon, the loop is started, and can only be stopped with break, so wait(3) will not run.

2 answers

✓ Accepted answer

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.

8 comments

0

What if I needed two loops to run at once? How would I handle that?

0

I would do a function or a do code block.

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.

0

Or a do statement (I don't really know what they're called anyways).

0

I think "do" could run in the background, but I'm not 100% sure.

0

You could use also threads such as delay and spawn.

0

spawn(function() end) works

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

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