lua 协程的理解

参考链接: 

      http://www.cnblogs.com/zrtqsk/p/4374360.html

对例子的自我理解:

--  协程的理解
--  co  是协程的内容,类似函数内容,  通过yield 将中止函数的操作,
--  但重新resume后,将继续执行co未执行到内容

function foo(a)
    print("foo", a)
    return coroutine.yield(2 * a)
end

co = coroutine.create(function ( a, b )
    print("co-body", a, b)
    local r = foo(a + 1)
    print("co-body", r)
    local r, s = coroutine.yield(a + b, a - b)
    print("co-body", r, s)
    return b, "end"
end)




--  resume首次传递参数  yield 返回true 与 yield的参数
local  c, d = coroutine.resume(co, 1, 10)
print("main:", c, d)
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))



--  执行结果   
-- co-body 1   10
-- foo 2
-- main    true    4



-- co-body r
-- main    true    11  -9

-- co-body x   y
-- main    true    10  end


-- main    false   cannot resume dead coroutine

lua协程是协作式多任务,用于异步通信的机制,参考链接:

 http://blog.csdn.net/sharemyfree/article/details/47442115

原文地址:https://www.cnblogs.com/hzijone/p/7591576.html