闭包,协程

array = {"Google", "Runoob"}

function elementIterator (collection)

   local index = 0

   local count = #collection

   -- 闭包函数

   return function ()

      index = index + 1

      if index <= count

      then

         --  返回迭代器的当前元素

         return collection[index]

      end

   end

end

for element in elementIterator(array)

do

  print(element)

end

这里写了一个迭代器,是一个多状态的迭代器,和无状态的迭代器的区别在于,它每次执行会存储index的的状态,依次递增,来实现迭代器的功能。如果不在迭代器里使用,那可以这样通过简单方法使用:

c1=elementIterator(array)

c1(array)--输出Google

c1(array)--输出Runoob

闭包有个问题在于内存泄漏,在GC中无法回收。当通过c1调用完之后,要通过c1=nil让它不再引用。

 

协同程序

 

local newProductor

function productor(min)

     local i =min

     while true do

          i = i + 1

          send(i)     -- 将生产的物品发送给消费者

     end

end

 

function consumer(min,max)

local j=min

     while j<max do

          j = receive(min)     -- 从生产者那里得到物品

          print(j)

     end

end

 

function receive(min)

     local status, value = coroutine.resume(newProductor,min)

     return value

end

 

function send(x)

     coroutine.yield(x)     -- x表示需要发送的值,值返回以后,就挂起该协同程序

end

 

-- 启动程序

newProductor = coroutine.create(productor)

consumer(10,300)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值