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)