Stop a function while it's in the middle of running

How can I create a script as follows:

local function Run()
 warn(1)
 task.wait(1)
 --should stop in the middle here
 warn(2)
 task.wait(1)
 warn(3)
end)

Coroutines won’t work as I need a way to stop it outside of its self.

4 Likes

You can use break or return, it will stop the function from running the lines below break or return.

coroutines would really help you with this.

and as far as i know, return will just completely end the function, while returning some data.
there might be away tho

break only works for loops.

Right, but that has to be called inside of the thread

You can use local connection = Run(), and then connection:Disconnect()

False. Creating a function does not return a Connection object. That only works if you are creating an event.

3 Likes

Wont work; you can’t yeild a coroutine outside of itself

A local function is not a connection object

Thank you for the advice. @cxiqlne , I found out you can do it with task library.

local function foo()
	task.wait(1)
	print("This won't print if a line cancels the function 'foo'.")
end

local thread = task.spawn(foo)
task.cancel(thread)
15 Likes

same thing with the coroutine library

local thread = coroutine.wrap(foo)
thread()

coroutine.close(thread)

-- or:
local thread = coroutine.create(foo)
coroutine.resume(thread)

coroutine.close(thread)
6 Likes

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