1. 程式人生 > >csdn學習筆記一:lua 迭代器

csdn學習筆記一:lua 迭代器

 

無狀態的迭代器(不使用閉包方式),

ipairs函式

a = {10,20,30,40,50,60}
for k,v in ipairs(a) do 
    print(k,v);
end
-----------------------------
output:
1       10
2       20
3       30
4       40
5       50
6       60

無狀態迭代器實現

function square(mx, idx)
            if idx < mx then
                idx = idx + 1;
                return idx, idx * idx;
            end
end

for i,n in square,3,0 do  
    print(i,n);
end
------------------------------------------
output:
1       1
2       4
3       9

for end迴圈原型是這樣的

do
    local _f, _s, _v = square,3,0
    while true do
        local k,v = _f(_s,_v);
        _v = k;
        if k == nil then break; end
        print(k,v);
    end
end

上面for如何把square,3,0變換成ipairs(3)這種型別

function square(mx, idx)
            if idx < mx then
                idx = idx + 1;
                return idx, idx * idx;
            end
end


function squareX(n)
    return square,n,0
end

for i,n in squareX(3) do
    print(i,n);
end
------------------------------------
output:
1       1
2       4
3       9

案例二、列印table資料(有狀態迭代器實現,使用閉包)


arr = {"hello","lua","fangfang"};

function traverse(arr)
    local idx = 0;
    local count = #arr;
    return function (...)
        idx = idx + 1;
        if idx <= count then
            return idx,arr[idx];
        end
    end
end

for k,v in traverse(arr) do 
    print(k,v);
end
-----------------------
output:
1       hello
2       lua
3       fangfang

無狀態迭代器實現(不使用閉包)

arr = {"hello","lua","fangfang"};

function iterator(arr,idx)
    idx = idx + 1;
    if idx <= #arr then
        return  idx,arr[idx];
    end
end

function traverse(arr)
    return iterator,arr,0;
end

for k,v in traverse(arr) do 
    print(k,v);
end
---------------------------------------------
output:
1       hello
2       lua
3       fangfang

案例三、有狀態迭代器

arr = {10, 20, 30, 80, 40, 50, 60};

function myItr(arr)
    local i = 0;
    return function()
        i = i + 1;
        if arr[i] then 
            return i,arr[i]; 
        end
    end
end

for k,v in myItr(arr) do 
    print(k,v);
end
---------------------------------------
output:
1       10
2       20
3       30
4       80
5       40
6       50
7       60

原型

do
    local _f, _s, _v = myItr(arr);
    while true do
        local k,v = _f(_s,_v);
        _v = k;
        if k == nil then break; end
        print(k,v);
    end
end
--------------------------------------
output:
1       10
2       20
3       30
4       80
5       40
6       50
7       60