Coroutines are a very powerful feature that allow two executions to "work together".
Two coroutines use coroutine.resume
and coroutine.yield
to communicate with each other and "hand off" execution.
The simplest way for two coroutines to "work together" is to completely ignore each other and just take turns doing work. This is how ROBLOX gets the appearance of "multitasking": wait()
causes the current coroutine to stop working and lets another coroutine start working.
If you're only using coroutine
to make two threads work "at the same time", don't use coroutine.
Instead, use spawn
to create a "thread" in the background.
See this thread for examples of (not) using spawn to great effect.
Consider the following function that produces prime numbers:
03 | function computePrimes() |
06 | while #primes < 1000 do |
08 | for _, smallerPrime in ipairs (primes) do |
10 | if i % smallerPrime = = 0 then |
16 | table.insert(primes, i) |
The above function produces a list; you can use a simple loop to print out the first 1000 primes:
1 | for _, prime in ipairs (computePrimes()) do |
Or you could do something like, compute the sum of all of the primes under 10000:
2 | for _, prime in ipairs (computePrimes()) do |
There are two main problems with this approach.
1) computePrimes()
might not have made enough primes; it's possible it stopped too early
2) computePrimes()
might have wasted time making way more primes than we need; it's possible the loop doesn't even cover most of the list.
We could plumb this information into computePrimes
, but that would make computePrimes
much more complicated.
The solution is to use coroutines; then computePrimes
will be a generator that produces 1 prime at a time:
01 | primeComputer = coroutine.wrap( function () |
04 | for i = 2 , math.huge do |
06 | for _, smallerPrime in ipairs (primes) do |
08 | if i % smallerPrime = = 0 then |
14 | table.insert(primes, i) |
I use coroutine.wrap
as a convenience, I won't give an example here that uses coroutine.resume
/ coroutine.create
manually.
Now, we can write our loop and compute exactly the set of primes we want:
04 | local prime = primeComputer() |
06 | if prime > = 10000 then |