9.Lua迭代器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27032631/article/details/87923179

Lua迭代器

迭代器 是一种对象,它能够用来遍历标准容器中的元素,每个迭代器对象代表容器中确定的地址,在Lua中迭代器支持指针类型的结果,它可以便利集合的每一个元素。

泛型for迭代器

泛型for 提供了集合的key/value对

table={}
for k,v in pair(table) do
   print(k,v)
end   

在Lua中我们常常使用函数来描述迭代器,每次调用该函数就返回集合的下一个元素。Lua 的迭代器包含以下两种类型:

  • 无状态迭代器
  • 多状态迭代器
无状态迭代器
   function square(iteratorMaxCount,currentNumber)
   if currentNumber<iteratorMaxCount
   then
      currentNumber = currentNumber+1
   return currentNumber, currentNumber*currentNumber
   end
end

for i,n in square,3,0
do
   print(i,n)
end


结果:
1	1
2	4
3	9

多状态 迭代器
arry={"Lua","chuanwei"}

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 e in elementIterator(arry) do

   print(e)

end

结果:
Lua
chuanwei

猜你喜欢

转载自blog.csdn.net/qq_27032631/article/details/87923179