迭代和协程
来源:互联网 发布:万网注册域名流程 编辑:程序博客网 时间:2024/05/01 23:54
3.迭代
function enum(array) local index=1 return function() local ret=array[index] index=index+1 return ret end end--遍历function foreach(array,action) for element in enum(array ) do action(element) endend--指定action为打印foreach({1,2,3},print)
运行结果:
4.协程(生产者和消费者的问题)
--producerfunction producer() return coroutine.create( function(salt) local t={1,2,3} for i=1,#t do salt=coroutine.yield(t[i]+salt) end end)end --consumer 参数为生产者生产的结果function consumer(prod) local salt=10 while true do local running,producer=coroutine.resume(prod,salt) salt=salt*salt if running then print(producer or "end") else break end endendconsumer(producer())
运行结果:
在做完t[i]+salt之前,协程还处于running的状态,而后直接挂起,producer的值为11;
第二次yield之前,salt的值已经变为100,加上t[2],为102,以此类推
阅读全文
0 0
- 迭代和协程
- 线程、进程和协程
- 线程、进程和协程
- 线程、进程和协程
- 非阻塞和协程
- 线程和协程
- 进程、线程和协程
- 有关python生成器和协程
- 子弹追踪和协程应用
- python 线程、进程和协程
- python异步IO和协程
- Python Generator函数和协程
- [转]进程、线程和协程
- 线程和协程的异同!
- 2.19 WWW类和协程
- Python中的生成器和协程
- 进程、线程和协程的理解
- 关于线程Thread和协程Coroutine
- PAT basic 1063
- Android中的动画1(补间动画)
- node 获取当前文件路径
- 快速排序
- 目录:《C++程序设计教程》-传智播客
- 迭代和协程
- PAT basic 1064
- python argparse (2)
- 【CodeForces
- spring整合dubbo时xml配置文件问题
- PAT basic 1065
- iOS使用MobileVLCKit播放rtsp视频流
- 打造基于Clang LibTooling的iOS自动打点系统CLAS(一)
- 原型跟原型链