Help with coroutines please!

So, i was just wondering if I could turn this code, which has a task.spawn function, into a coroutine, as I need to be able to play and pause the coroutine, which I’m pretty sure the task.spawn feature does not have.

task.spawn(function()
	while task.wait(0.1) do
		if(enemy.getPlayerInView() ~= nil) then
			enemy.FollowPlayer(game.Players.forkyplayss.Character, workspace.enemy)
		end
	end
end)
--RS.Stepped:Connect(function()
while task.wait() do
	enemy.PathFind(workspace.enemy)
end
1 Like

When I originally was learning corouties and lua in general, I found this video quite useful as it shows how simple coroutines can be.

Hopefully this could help.

(P.S. timestamp at 1:50)

1 Like
--create a coroutine for the function
local randomFunc = coroutine.create(function()
    --code here
end)

--call the coroutine asynchronously
coroutine.resume(randomFunc)
1 Like

When you do:

coroutine.create() it doesn’t start the thread, unlike task.spawn

So all you have to do to start it is: coroutine.resume(thread), and to pause it, coroutine.yield(thread)

ex:

local myThread = coroutine.create(function() --- doesn't run until resume is called
 print("I'm a thread!")
end)

coroutine.resume(myThread) -- starts it
task.wait()

coroutine.yield(myThread) -- pauses


1 Like

Whether created through the task library, or through the coroutine library, the end result is the same. You end up with a Lua/u ‘thread’ object. This means that functions from either library can largely be used interchangeably.

While it is generally preferred to stick to one library over the other, there are exceptions. In that, the task library does not necessarily supersede the coroutine library. General utility functions such as coroutine.status, coroutine.yield, and coroutine.running, remain practical in either case.

Thus, code like this is without issue

-- It's generally a good idea to use variables like AwaitingResumption
-- to differentiate your yields, from yields to the scheduler.
-- Not necessary in the example below; but this is still how it would be done.
local AwaitingResumption = false
local YieldingThread = task.spawn(function()
	local ResumeCount = 0
	while true do
		AwaitingResumption = true
		coroutine.yield()
		AwaitingResumption = false
		ResumeCount += 1
		print(`Resumed {ResumeCount} times!`)
	end
end)

-- task.spawn called on a function, creates a thread from that function
-- however, task.spawn called on a thread, merely resumes that thread.
if AwaitingResumption then
	task.spawn(YieldingThread)
end
1 Like