"Lua coroutine.yield(-1)" 的含义是什么?

coroutine.yield(-1) 是什么意思?我不明白这里的 -1

代码片段和输出如下:

> function odd(x)
>>   print('A: odd', x)
>>   coroutine.yield(x)
>>   print('B: odd', x)
>> end
>
> function even(x)
>>   print('C: even', x)
>>   if x==2 then return x end
>>   print('D: even ', x)
>> end
>
> co = coroutine.create(
>>   function (x)
>>     for i=1,x do
>>       if i==3 then coroutine.yield(-1) end
>>       if i % 2 == 0 then even(i) else odd(i) end
>>     end
>>   end)
>
> count = 1
> while coroutine.status(co) ~= 'dead' do
>>   print('----', count) ; count = count+1
>>   errorfree, value = coroutine.resume(co, 5)
>>   print('E: errorfree, value, status', errorfree, value, coroutine.status(co))
>> end
----    1
A: odd  1
E: errorfree, value, status     true    1       suspended
----    2
B: odd  1
C: even 2
E: errorfree, value, status     true    -1      suspended
----    3
A: odd  3
E: errorfree, value, status     true    3       suspended
----    4
B: odd  3
C: even 4
D: even         4
A: odd  5
E: errorfree, value, status     true    5       suspended
----    5
B: odd  5
E: errorfree, value, status     true    nil     dead
>

-1 表示在协程中返回一个值为 -1 的 yield 语句。在这段代码中,当 i 等于 3 时,会执行 coroutine.yield(-1)。这会使得协程暂停,并向主代码返回值为 -1。主代码继续运行,直到下一次调用协程的 coroutine.resume 方法。coroutine.resume 方法将协程从暂停状态恢复,并传递一个新的值给协程。在这个例子中,值为 5。协程从 coroutine.yield 语句处继续执行,直到完成所有循环。最后一次调用 coroutine.resume 方法将协程置为死亡状态。

点赞
用户108741
用户108741

coroutine.yield (···)

暂停调用协程的执行。协程不能正在运行C函数、元方法或迭代器。任何传递给 yield 的参数都作为额外结果传递给 resume

http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield】

换句话说,-1 可以是任何值,甚至多个值,这些值的使用方式由程序员决定。

2013-12-03 05:16:23
用户1009479
用户1009479

任何传递给相应coroutine.yield的参数,都会被coroutine.resume返回。所以,在这里coroutine.yield(-1)中的-1并没有什么特殊之处,它类似于函数odd(x)中的coroutine.yield(x)

它在counter2i3时执行。相应的输出是:

----    2
B: odd  1
C: even 2
E: errorfree, value, status     true    -1      suspended

在显示ture(表示无误)之后,你注意到这里的-1吗?那就是调用coroutine.yield(-1)的返回值,它最终成为了coroutine.resume的返回值。

出于同样的原因,coroutine.resume的其他返回值都是135,这些值都来自函数odd(x)中的coroutine.yield(x)

2013-12-03 05:18:32