lua练习23-实现pairs和ipairs

2020-10-15  本文已影响0人  GameObjectLgy
--实现ipairs和pairs功能
--pairs 无序遍历
--ipairs 以1递增遍历

require("LuaUitl")

local function MyIPairsIter(table, i)
    i = i + 1
    local value = table[i]
    if value then
        return i, value
    end
end

local function MyIPairs(table)
    return  MyIPairsIter, table, 0
end

local PairsIter = function (table, key)
    return next(table, key)--lua nei内置函数
end

local function Mypairs(table)
    return PairsIter, table, nil
end


---test
TestTable0 = {1, 2, 3, 6, ["1"] = "a"}
TestTable1 = {1, 2, 4, 3, 5, 8}
TestTable2 = {"2", ["4"] = "12", [1]= 5, {8, "aa"}}

-- for key, value in Mypairs(TestTable1) do
--     print(key, value)
-- end
-- print("----------------------")
-- for key, value in Mypairs(TestTable2) do
--     print(key, value)
-- end
-- print("||||||||||||||||||||||")
-- for key, value in pairs(TestTable2) do
--     print(key, value)
-- end

for key, value in ipairs(TestTable0) do
    print(key, value)
end
print("---------------------------")
for key, value in MyIPairs(TestTable0) do
    print(key, value)
end
上一篇 下一篇

猜你喜欢

热点阅读