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()
相关文章推荐
- C++调用LUA函数,可变参模板实现
- LeetCode150 Evaluate Reverse Polish Notation java题解
- 读取xml生成lua测试代码
- Lua学习之类型与值
- Lua学习之类型与值
- Lua学习笔记之开始
- lua userdata
- lua垃圾回收机制
- Lua中使用二维数组实例
- lua学习--记录(2)
- Lua math.fmod使用时的小数问题
- .NET平台开源项目速览(8)Expression Evaluator表达式计算组件使用
- Ubuntu14.04 安装lua5.3
- Wireshark Lua插件学习心得
- Lua的string学习笔记
- Lua 与C/C++ 交互系列:动态注册枚举enum到Lua Code中,在运行时在Lua Code中获取内省信息
- LUA常见库和工具
- Lua 与C/C++ 交互系列:注册枚举enum到Lua Code中
- [文学阅读] METEOR: An Automatic Metric for MT Evaluation with Improved Correlation with Human Judgments
- lua string.dump