Lua 5.3 迭代器的简单示例

Lua 5.3 迭代器的简单示例

 

创建”closure”模式的”iterator”

function allowrds()
    local line = io.read()
    local pos = 1
    return function ()
        while line do
            local s, e = string.find(line, "%w+", pos)
            if s then
                pos = e + 1
                return string.sub(line, s, e)
            else
                line = io.read()
                pos = 1
            end
        end
        return nil
    end
end

for word in allowrds() do
    print(word)
end

 

 结果运行现象:

 

 

创建”complex state iterator”模式的”iterator”

function iter(state)
    while state.line do
        local s, e = string.find(state.line, "%w+", state.pos)
        if s then
            state.pos = e + 1
            return string.sub(state.line, s, e)
        else
            state.line = io.read()
            state.pos = 1
        end
    end
    return nil
end

function allowrds()
    local state = {line = io.read(), pos = 1}
    return iter, state
end

for word in allowrds() do
    print(word)
end

 

 

 结果运行现象:

 

posted @ 2017-10-26 19:26  lsgxeva  阅读(254)  评论(0编辑  收藏  举报