|
| 1 | +# Coroutine |
| 2 | + |
| 3 | +## Overview |
| 4 | + |
| 5 | +Coroutine differs from the abstraction of thread from other languages, coroutine has more collaborative nature while thread are primitively parallel. |
| 6 | +That is, coroutine in lua is neither concurrent nor parallel, lua is like single-threaded, handles only one thing at a time and can switch control between coroutines. |
| 7 | +Thusly, one should never use words such as *thread* or *multi-threading* when introducing the use of lua coroutine. |
| 8 | + |
| 9 | +> [!NOTE] |
| 10 | +> Interestingly, coroutine in `lua` has type name `thread`, even though it is not a real thread. |
| 11 | +
|
| 12 | +- `coroutine.create(fn: function): thread`: coroutine factory |
| 13 | +- `coroutine.status(co: thread): string`: status of a coroutine |
| 14 | + - `running`: yeah it's running |
| 15 | + - `normal`: |
| 16 | + - `suspended`: created but not started, or suspended on half way |
| 17 | + - `dead`: terminated due to error |
| 18 | +- `coroutine.yield(...any): ...any`: return control back to caller, suspend the containing coroutine(should call it inside coroutine function body) |
| 19 | + - could pass arbitrary return values that could be captured by outer `coroutine.resume` |
| 20 | + - can capture arbitrary values as return values from outer `coroutine.resume` **after resume**. |
| 21 | + - of course `return` can also return values but terminates coroutine, no worry. |
| 22 | +- `coroutine.resume(co: thread, args: ...any): boolean, ...any`: **a blocking operation** to start or resume a `suspended` coroutine |
| 23 | + - returns `boolean` indicating whether resume succeeded and `...any` returned from the resumed coroutine by `coroutine.yield`. |
| 24 | + - supports passing args to the wrapped function of the coroutine |
| 25 | +- `coroutine.wrap(fn: function): function`: wrap resumption as a capsulated function for simplicity. |
| 26 | + |
| 27 | +## Coordination |
| 28 | + |
| 29 | +Coordination is viable by two basic functions, `coroutine.resume` and `coroutine.yield`. |
| 30 | +`coroutine.resume` starts or re-enter the coroutine by optional arguments, such arguments can be arguments for the coroutine function body **on first start**, or as new arguments passed halfway that can be captured by `coroutine.yield` on resume. |
| 31 | +Conversely, `coroutine.yield` can hang current coroutine and return values that can be captured by outer `coroutine.resume`. |
| 32 | + |
| 33 | +## The Stack |
| 34 | + |
| 35 | +> A coroutine is similar to a thread (in the sense of multithreading): a line of execution, with its own stack, its own local variables, and its own instruction pointer; |
| 36 | +> but sharing global variables and mostly anything else with other coroutines. |
| 37 | +> — Programming in Lua, Roberto Ierusalimschy |
| 38 | +
|
| 39 | +Each coroutine created in lua has its own stack to store the state of variables and so on. The stack would collected when thread is *dead* or no longer referenced by any variable. |
| 40 | + |
| 41 | +## Iterate by Coroutine |
| 42 | + |
| 43 | +Iterator and coroutine are spiritual cousins in lua, one can implement a iterator using coroutine. |
| 44 | + |
| 45 | +- stores state |
| 46 | +- yields value on *each call* |
| 47 | + |
| 48 | +```lua |
| 49 | +-- an infinite iterator |
| 50 | +local co = coroutine.create(function() |
| 51 | + local num = 0 |
| 52 | + while true do |
| 53 | + num = num + 1 |
| 54 | + coroutine.yield(num) |
| 55 | + end |
| 56 | +end) |
| 57 | +-- each time you resume is like iterate to next item |
| 58 | +local _, nxt = coroutine.resume(co) |
| 59 | +_, nxt = coroutine.resume(co) |
| 60 | +_, nxt = coroutine.resume(co) |
| 61 | +_, nxt = coroutine.resume(co) |
| 62 | +``` |
| 63 | + |
| 64 | +An implementation for `ipairs` using coroutine would be like this: |
| 65 | + |
| 66 | +```lua |
| 67 | +--- my ipairs at home using coroutine |
| 68 | +--- @generic T |
| 69 | +---@param arr T[] |
| 70 | +---@return fun(): integer, T |
| 71 | +local function iter_arr(arr) |
| 72 | + local idx = 1 |
| 73 | + -- the coroutine itself is part of the state |
| 74 | + local co_iter = coroutine.create(function() |
| 75 | + while idx <= #arr do |
| 76 | + coroutine.yield(idx, arr[idx]) -- yield current |
| 77 | + idx = idx + 1 |
| 78 | + end |
| 79 | + end) |
| 80 | + -- each call on the iterator should resume the coroutine |
| 81 | + return function() |
| 82 | + local _, i, val = coroutine.resume(co_iter) |
| 83 | + return i, val |
| 84 | + end |
| 85 | +end |
| 86 | + |
| 87 | +for idx, value in iter_arr { 1, 2, 3, 4, 5 } do |
| 88 | + print(idx, value) |
| 89 | +end |
| 90 | +``` |
| 91 | + |
| 92 | +## Wrap Coroutine as Function |
| 93 | + |
| 94 | +Coroutine can be like a consumer which would probably be called for one or more times, it could be trivial to write with plain `_, _ = coroutine.resume(co)` especially when the resumption has return value. |
| 95 | + |
| 96 | +```lua |
| 97 | +local co = coroutine.create(function() |
| 98 | + while true do |
| 99 | + coroutine.yield(math.random(1, 100)) |
| 100 | + end |
| 101 | +end) |
| 102 | + |
| 103 | +local _, nxt = coroutine.resume(co) |
| 104 | + _, nxt = coroutine.resume(co) |
| 105 | + _, nxt = coroutine.resume(co) |
| 106 | +``` |
| 107 | + |
| 108 | +With `coroutine.wrap()`, you can enclose it as a function, the function call does not return resumption status as `coroutine.resume` does. |
| 109 | + |
| 110 | +```lua |
| 111 | +local consume = coroutine.wrap(function() |
| 112 | + while true do |
| 113 | + coroutine.yield(math.random(1, 100)) |
| 114 | + end |
| 115 | +end) |
| 116 | + |
| 117 | +local nxt = consume() |
| 118 | +nxt = consume() |
| 119 | +nxt = consume() |
| 120 | +nxt = consume() |
| 121 | +``` |
| 122 | + |
| 123 | +> [!IMPORTANT] |
| 124 | +> The price of `coroutine.wrap` is, you can't track the status of the coroutine since it was wrapped inside. |
| 125 | +
|
| 126 | +> [!NOTE] |
| 127 | +> The implementation of `coroutine.wrap` can be like this: |
| 128 | +>```lua |
| 129 | +>--- my coroutine.wrap at home |
| 130 | +>---@param fn fun(...any): ...unknown |
| 131 | +>---@return fun(...any): ...unknown |
| 132 | +>local function wrap(fn) |
| 133 | +> local co = coroutine.create(fn) |
| 134 | +> return function(...) |
| 135 | +> local result = { coroutine.resume(co, ...) } |
| 136 | +> if result[1] then return select(2, unpack(result)) end |
| 137 | +> end |
| 138 | +>end |
| 139 | +>``` |
0 commit comments