Lua合作计划收益率(-1)和#x27;什么意思?
Lua合作计划收益率(-1)和#x27;什么意思?,lua,coroutine,Lua,Coroutine,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
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
>
协程产量(··)
暂停调用协同例程的执行。协同程序不能运行C函数、元方法或迭代器任何要产生的参数都将作为额外结果传递给恢复。
因此,换句话说,
-1
可能是任何值,甚至是多个值,这些值的使用方式取决于程序员。传递给相应的coroutine.yield
的任何参数都由coroutine.resume
返回。因此,coroutine.yield(-1)
中的-1
这里没有什么特别之处,它类似于函数odd(x)
中的coroutine.yield(x)
当计数器
为2
且i
为3
时执行。相应的输出为:
---- 2
B: odd 1
C: even 2
E: errorfree, value, status true -1 suspended
在表示无错误的ture
之后,请参见此处的-1
?这是对coroutine.yield(-1)
的调用的值,它最终作为coroutine.resume
的返回值
出于类似的原因,coroutine.resume
的其他返回值是1
、3
和5
,它们都来自函数odd(x)
中的coroutine.yield(x)