How to stop a game session in my script

local RoundController = {}

local CanContinue = false

local EndFunc = nil

RoundController.Run = function(RoundFirstStart, RoundFinalEnd, RoundStartLoop, RoundEndLoop)
	EndFunc = RoundFinalEnd
	CanContinue = true
	RoundFirstStart()
	task.wait(10)
	if not CanContinue then return end
	while CanContinue do
		RoundEndLoop()
		if not CanContinue then return end
		task.wait(5)
		if not CanContinue then return end
		RoundStartLoop()
		if not CanContinue then return end
		task.wait(10)
		if not CanContinue then return end
	end
end

RoundController.Cancel = function()
	print("Canceled")
	EndFunc()
	CanContinue = false
end



return RoundController

The issue here is that if the round ends and then a new one starts before one of the timers is up it will continue the old round.
Example

Round ends
Waits 2 seconds
New Round Starts
Waits 3 seconds
Old round’s next function is ran

My script doest cancel the old round. How can i fix this? i know you can do something like a cancel on a task.wait, so what do i do? Im new to making round based games and idk what im doing

Not sure exactly what you meant, but I am assuming the old game loop persists even after the game’s end? Then, you can make a thread to handle the loop. To simplify things, just use the task library to create/stop threads (coroutines here).

Example:

local RC = {}

local Thread
RC.Run = function()
	if Thread then
		task.cancel(Thread)
		Thread = nil
		return
	end
	
	Thread = task.spawn(function()
		while task.wait() do
			warn("LOOPING")
		end
	end)
end

RC.Stop = function()
	if Thread then
		task.cancel(Thread)
		Thread = nil
	end
end

return RC
1 Like

does stopping a thread also cancel any task.waits in it?

Yes, it stops and ends the encapsulated code.