How to disconnect a while loop inside a coroutine

I have this function that handles skipping of dialogue, however I can call it several times, but I don’t it to be running 7 different times. So I basically want it to stop running when called again.

local function SkipDialogueHandler()
	-- Handle skipping of dialogue (if player skips)
	coroutine.wrap(function()
		while InDialogue do
			if not InDialogue then break end
			
			if TextFinished then break end
			
			if InitialTextObject then
				if SkipDialogue then -- Dialogue skipped, show text in full
					InitialTextObject:Show()
					TextFinished = true

					break
				end
			end
			print("IN DIALOGUE")
			task.wait()
		end
	end)()
end

--// example (this isn't what I do in the code, but codes too long to show here)
SkipDialogueHandler()

task.wait(2) -- Time between calls

SkipDialogueHandler()

And so this result in this while loop running twice

2 Likes

One method is to return a cancel function

Here is an example of it in use cancelling a pathfinding coroutine loop.

The second method is using promises which also has a built it cancel function implementation possibility.

A break statement to break out of a while loop, coroutine.yield() to suspend the active coroutine.