Way to cancel threads inside of a table?

Basically, I’ve been wanting to make a controller that is able to run certain functions when I call them. I wanted to use a table to do this, but, as seen through the code below, I can’t seem to figure out a way to cancel the thread “Run”. I can’t seem to find a way to allow the script to recognize Run.

local functions = {
	["Test"] = {
		Run = task.spawn(function()
			print("Running")
			
			task.wait(5)
			
			print("Still Running")
		end),
		Cancel = function()
			print("Canceled")
			
			task.cancel(Run)
		end,
	}
}

(Run is underlined on the cancel function)

Run doesn’t exist in this context. You will have to set up your table like this:

local functions = {
	["Test"] = {
		Run = task.spawn(function()
			print("Running")

			task.wait(5)

			print("Still Running")
		end),
	}
}

function functions.Test:Cancel()
	task.cancel(self.Run)
end
1 Like

Thanks! I was wondering if I could’ve done that but I didn’t want to confuse myself too much.

I know you already solved my problem, but when I run the function like
functions[“Test”].Run(), it gives me the error "attempt to call a thread value " and I’m not sure why. (It runs the first print then fires that error)

task.spawn runs the thread immediately; you would do this alternatively:

Run = coroutine.create(function()
   --content
end)

and you would run the thread using:

coroutine.resume(functions.Test.Run)

Thanks! Works as intended. I prefer using task.spawn over coroutines and they have basically the same functionality so I didn’t think I would need to use them.

However, is there a way to just start the coroutine from the start after cancelling it? I set functions.Test:Cancel() to yield the coroutine. (Asking this because if I were to create a new coroutine thread, I don’t think it would be connected to the test function again.

If I’m understanding correctly, you’re asking how to restart a thread after closing it: you would have to create a new coroutine. I recommend having a separate function that you can use to define inside the coroutine:

local function Thread_Run()
    --...
end

--...
function functions.Test:Cancel()
    task.cancel(self.Run) -- Do something to end the thread
    self.Run = coroutine.create(Thread_Run) -- Create a new thread
end

If this isn’t what you asked for, please let me know

Thanks for all your help. Solved this problem on my own by just saving the coroutines on a table and canceling them using that.

Quick question: Can you cancel a coroutine using task.cancel() or was that just from before.

You can use both task.cancel and coroutine.close

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