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
>
最佳答案
传递给相应coroutine.yield
的任何参数都由coroutine.resume
返回。所以这里的coroutine.yield(-1)
中的-1
没什么特别的,它类似于coroutine.yield(x)
中的函数奇数(x)
。
当counter
为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)
。
关于Lua coroutine.yield(-1)的含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20343097/