Lua中 ipairs 与 pairs 的自定义实现

Lua 中 ipairs 与 pairs 功能的自定义实现

iparis

local function myipairs(tbl)
    return function(state, control) -- iterator
        control = control + 1
        local value = tbl[control]
        if value == nil then
            return nil, nil
        end
        return control, value
    end, nil, 0, nil
end

local tb1 = {2, 3, 4, 5}
for index, value in myipairs(tb1) do
    print(index, value)
end

pairs

local function mypairs(tbl)
    return function(state, control) -- iterator
        control = next(tbl, control)
        local value = tbl[control]
        return control, value
    end, nil, nil, nil
end

local tb = {aa = "bb", 3, 4, 5}
for key, value in mypairs(tb) do
    print(key, value)
end
posted @ 2021-07-15 17:39  withpear  阅读(613)  评论(0)    收藏  举报