Is it possible to make a function that you can cancel at any time?

I was wondering if you could stop the execution of like a subroutine at any point in its execution.
For example

local this = function()
 while wait() do
  print(“hi”)
 end
end)
this()

someEvent.Event:Connect(function()
 this:Cancel()
end)
1 Like

You can’t do this with pure co-routines or regularly scheduled Lua threads IIRC. The best way to do this would to take the simple approach, (ie; check for a termination variable in the loop), or to write a generic Task scheduling system.

1 Like

How would I go about writing a task scheduling system?

The complexity/scope would really depend on your application. Is your goal to be able to have multiple for-loops that sequentially execute? or just a single while-loop that continuously runs some code?

It’s pretty much a single while loop

Do you maybe happen to know a reference I could read?

After some quick googling, this looks like a nice guide with code examples. (gave it a very brief glance)

3 Likes

Oh wow this looks nice. Thanks for all your help Jody :slight_smile: