Coroutine help one coroutine is working, the other isn't

Hey apologies in advance i’m very new to coroutines and I’ve just started messing with them and I’m not exactly sure what I’m doing wrong? I’ve got two scripts and the first script includes a coroutine.wrap() function and it runs perfectly. However the second script using the same syntax isn’t firing? the second one is included after a while loop and I’m not sure if that’s the issue or not. since the first script runs a coroutine loop so that events can still be received and done things with while it checks stamina stuff in the background
first script (working)

--just on server event n such above here
coroutine.wrap(function()
	local players = game.Players:GetPlayers()
	while wait(1) do
		--decrease when sprinting
		if #sprinters >=1 then
			for i,v in pairs(sprinters) do
				local stamina = v.PlayerGui.statsManager.stats.stamina
				if stamina.Value >=0 then
					stamina.Value -= script.stamDec.Value
					if stamina.Value < 0 then
						stamina.Value = 0
					end
				end
				if stamina.Value <= 0 then
					local char = v.Character
					if char then
						local humanoid = char:FindFirstChild("Humanoid")
						if humanoid then
							humanoid.WalkSpeed = 12
							local tableNum = table.find(sprinters, v)
							table.remove(sprinters, tableNum)
						end
					end
				end
			end
		end
		--increase when not sprinting
		for i,v in pairs(players) do
			if not table.find(sprinters, v) then
				local stamina = v.PlayerGui.statsManager.stats.stamina
				if stamina.Value < 100 then
					stamina.Value += script.stamInc.Value
					if stamina.Value > 100 then
						stamina.Value = 100
					end
				end
			end
		end
		players = game.Players:GetPlayers()
	end
end)()

second script (not working coroutine, rest works fine)

--while loop above here
coroutine.wrap(function()
	while wait(1) do
		print("coro")
		if #messageQueue >= 1 then
			print(#messageQueue)
		end
	end
end)()

Try placing the while loop under the second coroutine.wrap(). I think it’s because it yielded everything else under it.

EDIT: You might also want to use task.spawn()

task.spawn(function() -- This will run the loop without yielding what comes after this
     -- Place your while loop in here
end)

-- Place your second coroutine under here

The second coroutine will only run once the while loop above finishes/"breaks’

1 Like

Thanks for tour help! whats the difference between task.spawn and a coroutine if you don’t mind me asking

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.