Lua 迭代器

来源:互联网 发布:js扩展window方法 编辑:程序博客网 时间:2024/05/16 10:42

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.

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

We can use this iterator in a while loop:

t = {10, 20, 30}iter = values(t)    -creates the iteratorwhile 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.

t = {10, 20, 30}for element in values(t) do    print (element)end
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    endend
0 0
原创粉丝点击