Are coroutines for multitasking?

Hello! Is coroutine basically an alternative to this:

local Event = Instance.new("BindableEvent")

Event.Event:Connect(function()
   print("Hello, Multitasking")
   task.wait(5)
   print("Doing very good!")
end)

Event:Fire()
print("This should be running while the multitasking.")
task.wait(2)
print("It is!")

I just don’t know what they are for, and I have been using my BindableEvent solution for multitasking in scripts.

If coroutines are the same thing, what is more efficient, and should I replace my BindableEvent solution with coroutines?

Thank you.

Depends on what you’re doing. Luau is still single threaded so it’s not true “multitasking” but you should use things based on your circumstances. BindableEvents are for creating same-environment signals while coroutines are for pseudothreading.

In the example you’ve given, at a cursory glance they will give virtually the same results but the underlying code differs. Coroutines aren’t signals so you can’t connect to them.

Think about it in English: there are two parts to the word, the prefix “co-” and the word “routine”. “Co-” means jointly and a routine is something that occurs. Therefore, a co-routine is a routine that is happening jointly with a routine. That routine would be the current thread which you can get by using coroutine.running. Anything that starts a thread is the routine and coroutines happen “alongside” it.

Do you need an event-driven system? BindableEvents. Do you have a scenario where you’d normally use parallel threading instead or a scenario where, for example, you don’t want a while loop to interrupt the execution of subsequent code? Coroutines or the task library. Neither is an alternative for the other and their efficiency comparison shouldn’t dictate what you need, rather your use case should.

2 Likes