lua自定义迭代器

闭合函数

    function diedaiqi(t)
        local i = 0
        return function()
            i = i + 1
            return t[i]
        end
    end

通过while

    local iter = diedaiqi(t)
    while true do
        local value = tier()
        if value == nul then
            break
        end

        print(value)
    end

通过for for循环只会调用一次dieDaiQi函数,然后把它的返回值保存起来。

    local t = {“fdsd”,”445”}
    for value in diedaiqi(t) do
        print(value)
    end

返回两个值的迭代器

    function diedaiqi(t)
        local i = 0
        return function()
            i = i + 1
            if i > #t then
                return nil
            end
            return i,t[i]
        end
    end

你可能感兴趣的:(lua)