lua协程的使用列子分析

来源:互联网 发布:淘宝客公众号系统搭建 编辑:程序博客网 时间:2024/06/10 04:19

例子一

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)endpd_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 valueendfunction consumer()  local y = 0  while true do    y = receive()    print("receive value is :",y)  endendconsumer()




 

0 0
原创粉丝点击