您的位置:首页 > 编程语言 > Lua

lua协程的使用列子分析

2015-06-30 11:46 543 查看

例子一

handle = coroutine.create(function (arg1,arge2)
local start = 0

print(arg1,arg2)

while true do
if( start == 0 or start == 20) then
print("yield arg is :",coroutine.yield(arg .. "me",arg2+1))
print("back to",start)
end

if start == 30 then
break
end

start = start + 1
print("it is first coroutine istance")
end

return "coroutine is over"

end)

print(coroutine.resume(handle,"test",1999))
print(coroutine.resume(handle,"ooo",33))
print(coroutine.resume(handle,"111",77))
print(coroutine.resume(handle,"jjj",55))


输出结果:

分析

第一次调用resume,此时没有对应的yield,它的参数时传递给匿名函数的

第二次调用resume,此时有对应的yield, 此时resume的作用是从函数yield返回,resume的参数正好传递给yield作为返回值(yield的第一个返回值是固定的,返回调用状态true or false)

第一次调用yield,并传递了参数,此时的yield参数是作为:让本次yield调用返回的(匿名函数继续执行,而不是卡在yield函数调用处),resume 调用的返回值。

例子二(生产者,消费者)

function send(x)
coroutine.yield(x)
end

pd_handle = coroutine.create(function ()
local x = 0
while true do
x = io.read()
send(x)
end)

fuction receive()
local status,value = coroutine.resume(pd_handle)
return value
end

function consumer()
local y = 0
while true do
y = receive()
print("receive value is :",y)
end
end

consumer()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: