您的位置:首页 > 编程语言 > Lua

Lua 迭代器

2016-01-27 10:17 337 查看
7.1 Iterators and Closures

In Lua, we typically represent iterators by functions: each time we call the function, it returns the “next” element from the collection.

[code]function values (t)
    local i =O
    return function () i = i + 1; return t[i] end
end


We can use this iterator in a while loop:

[code]t = {10, 20, 30}
iter = values(t)    -creates the iterator
while true do
    local element = iter()一一calls the iterator
    if element == nil then break end
    print (element)
end


however, it is easier to use the generic for.

[code]t = {10, 20, 30}
for element in values(t) do
    print (element)
end


[code]function allwords ()
    local line = io.read() -- current line
    local pos = 1 -- current position in the line
    return function () -- iterator function
        while line do -- repeat while there are lines
            local s, e = string.find(line, "%w+", pos)
        if s then -- found a word?
            pos = e + 1 -- next position is after this word
        return string.sub(line, s, e) -- return the word
        else
            line = io.read() -- word not found; try next line
            pos = 1 -- restart from first position
        end
    end
    return nil -- no more lines: end of traversal
    end
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: