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


#1

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)

#2

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.


#3

How would I go about writing a task scheduling system?


#4

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?


#5

It’s pretty much a single while loop


#6

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


#7

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


#8

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