# Lua 迭代器

## 通用迭代器

``````array = {"Lua", "Tutorial"}

for key,value in ipairs(array)
do
print(key, value)
end
``````

``````1  Lua
2  Tutorial
``````

• 无状态迭代器
• 有状态迭代器

## 无状态迭代器

``````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
``````

``````function square(iteratorMaxCount,currentNumber)
if currentNumber<iteratorMaxCount
then
currentNumber = currentNumber+1
return currentNumber, currentNumber*currentNumber
end
end

function squares(iteratorMaxCount)
return square,iteratorMaxCount,0
end

for i,n in squares(3)
do
print(i,n)
end
``````

``````1	1
2	4
3	9
``````

## 有状态迭代器

``````array = {"Lua", "Tutorial"}

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
``````

``````Lua
Tutorial
`````` ### 糖果 LUA教程

#### PLUM NIZ静电容键盘怎么样?

Published on September 25, 2020

#### 程序员如何选择合适的机械键盘

Published on September 18, 2020
{"ft_lang_label":"__label__zh","ft_lang_prob":0.88731605,"math_prob":0.98150593,"size":1789,"snap":"2021-04-2021-17","text_gpt3_token_len":971,"char_repetition_ratio":0.16414566,"word_repetition_ratio":0.1863354,"special_character_ratio":0.18949133,"punctuation_ratio":0.06926407,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9856238,"pos_list":[0,1,2,3,4,5,6],"im_url_duplicate_count":[null,null,null,null,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-01-20T07:54:04Z\",\"WARC-Record-ID\":\"<urn:uuid:59003871-bd73-46cf-bce1-4a55e3eb4a31>\",\"Content-Length\":\"34005\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:49a55c8d-d880-49ad-b8ba-ba7d0fc3d914>\",\"WARC-Concurrent-To\":\"<urn:uuid:b7d3d894-858c-4227-8c1f-2e675f4f2f0b>\",\"WARC-IP-Address\":\"185.199.110.153\",\"WARC-Target-URI\":\"https://lua.ren/lua_guide/iterators/\",\"WARC-Payload-Digest\":\"sha1:QF4HEEEHWSRGYY5A656BUKFJUPDTDX3X\",\"WARC-Block-Digest\":\"sha1:OFHBBBTWWHDLDQRJDZPDEZPQKAHSJQDR\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-04/CC-MAIN-2021-04_segments_1610703519923.26_warc_CC-MAIN-20210120054203-20210120084203-00798.warc.gz\"}"}