simplification
Download
74 lines 1.9 KiBNomsuModified 2026-11-08 raw
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
#!/usr/bin/env nomsu -V8.0.0
###
    This file defines the code that creates and manipulates coroutines
    
use "core/metaprogramming"
use "core/operators"
use "core/control_flow"

test:
    $fn =
        ->:
            yield 4
            yield 5
            repeat 3 times:
                yield 6
    
    $nums = {}
    for $ in (values yielded by (coroutine from $fn)):
        add $ to $nums
    assume ($nums deeply equals {4, 5, 6, 6, 6})
    assume ((values yielded by (coroutine from $fn)) deeply equals {4, 5, 6, 6, 6})
    $d = {.x = 0}
    $co =
        coroutine:
            $d.x += 1
            yield 1
            $d.x += 1
            yield
            $d.x += 1
    
    repeat while ((coroutine status of $co) != "dead"): resume $co
    assume ($d.x == 3)
    $co = (coroutine: yield 5)
    {$ok, $val} = (resume $co)
    assume ($ok == (yes))
    assume ($val == 5)
    $t = {}
    $i = 1
    for $ in
        values yielded by
            coroutine:
                yield 4
                yield 5
                yield
                yield 6
    ..:
        $t.$i = $
        $i += 1
    assume ($t deeply equals {4, 5, nil, 6})
    $t = {}
    for ($k = $) in
        values yielded by
            coroutine:
                yield 4
                yield 5
                yield
                yield 6
    ..:
        add {.key = $k, .value = $} to $t
    
    assume
        $t deeply equals {
            {.key = 1, .value = 4}, {.key = 2, .value = 5}, {.key = 3}, {.key = 4, .value = 6}
        }
public:
    (coroutine $body) parses as (coroutine from ->$body)
    ### Outside of a for loop's header, this collects every value the coroutine yields
    (values yielded by $coroutine) means:
        $values = {}
        for ($i = $value) in (values yielded by $coroutine):
            $values.$i = $value
        return $values
    
    ($ is a dead coroutine) means
        ((lua type of $) == "thread") and ((coroutine status of $) == "dead")