for循环pair和ipair解析

代码实现for循环中pair和ipair:

local strArray = {"123","456","789"}

local tmpTable = {}
tmpTable [1] = "11"
tmpTable [2] = "22"
tmpTable [3] = "33"
tmpTable [5] = "55"
tmpTable [8] = "88"
function listArray(array,index)
    print(string.format("call listArray %s.",index));
    index = index + 1
    if nil ~= array[index] then
        return index,array[index]
    end
end
function ipair(array)
    print("call iter");
    return listArray,array,0
end
for k,v in ipair(tmpTable) do
    print(string.format("%s ==> %s",k,v))
end

function pair(array)
    print("call listArray2")
    local nCount = #array
    local index = 0
    return function()
        print(string.format("call close func. %s",index))
        index = index + 1
        if index <= nCount then
            if nil ~= array[index] then
                return index,array[index]
            else
                while index <= nCount do
                    index = index + 1
                    if nil ~= array[index] then
                        return index,array[index]
                    end
                end
            end
        end
    end
end
print("=============   strArray2")
for k,v in pair(tmpTable) do
    print(string.format("%s ===> %s",k,v))
end
打印结果如下:
call iter
call listArray 0.
1 ==> 11
call listArray 1.
2 ==> 22
call listArray 2.
3 ==> 33
call listArray 3.
=============   strArray2
call listArray2
call close func. 0
1 ===> 11
call close func. 1
2 ===> 22
call close func. 2
3 ===> 33
call close func. 3
5 ===> 55
call close func. 5
8 ===> 88
call close func. 8

 

posted on 2018-06-20 15:00  魔天天  阅读(586)  评论(0)    收藏  举报