Nested Coroutines

Hello!
I’m currently working on a system where I create a coroutine that surrounds a while-loop that calls another coroutine. I’m not having trouble getting it to work, I’m just wondering if it’s a bad habit or just useless to be nesting coroutines. Here’s an example:

local findingTargets = coroutine.create(function()
    while wait(1) do
        MobModule.findPlayersInRange(Tables, MobModel, FollowRange)
        -- More code goes here
    end
end)
coroutine.resume(findingTargets)

The modulescript code is along these lines (P.S. I’m also wonder if it’s a bad habit to surround a coroutine.wrap() in a pcall):

findPlayersInRange = function(Tables, MobModel, Range)
	local findPlayersInRangeWrap = coroutine.wrap(function()
                   --code goes here
	end)

	local success, errormessage = pcall(function() findPlayersInRangeWrap() end)
	if(not success)then print(errormessage) end
end,

The reason I’m doing this is because I need the while-loop to be in it’s own thread so that I can have other functions running on the same script as the while-loop. I guess the real question is if I should get rid of the coroutine.wrap() and just have the code in the modulescript. Thanks!

Edit: Shout out to Pokemoncraft5290 for fixing my code formatting!

1 Like
local findingTargets = coroutine.create(function()
    while wait(1) do
        MobModule.findPlayersInRange(Tables, MobModel, FollowRange)
        -- More code goes here
    end
end)
coroutine.resume(findingTargets)

The modulescript code is along these lines (P.S. I’m also wonder if it’s a bad habit to surround a coroutine.wrap() in a pcall):

findPlayersInRange = function(Tables, MobModel, Range)
	local findPlayersInRangeWrap = coroutine.wrap(function()
                   --code goes here
	end)

	local success, errormessage = pcall(function() findPlayersInRangeWrap() end)
	if(not success)then print(errormessage) end
end,

Fixed code

2 Likes

if there is no reason to wrap that function in a pcall or coroutine, you shouldn’t do it.

1 Like

We don’t know if OP wants their code to yield or not. If they don’t want the code to yield due to the while loop, then yes they are necessary.

1 Like

With the first coroutine (while-loop) if the mob dies the code will yield, but it cannot yield for any other reason.

You could use spawn():

spawn(function()
    -- Loop
end

Spawn shouldn’t be used. In short, it can take very long, if ever, to run the function.

1 Like

It’s not malicious, the loops themselves create this error (“script timeout”) when it has no timeout, and if it really shouldn’t be used they would have removed it, it’s just an option.

Either way, it would be more useful to use Heartbeat.

1 Like

If it isn’t even guaranteed to run, why would you use it? Spawn is probably kept for backwards compatibility, like a lot of other stuff.

1 Like

You rarely want to use spawn, in fact I’d avoid using it all together as it can have issues.