2011-10-24 66 views
3

如何迭代lua中的表對元素對?我想實現循環和非循環迭代版本對的副作用免費方式。如何迭代lua中表中的元素對

I have table like this: 
t = {1,2,3,4} 

Desired output of non-circular iteration: 
(1,2) 
(2,3) 
(3,4) 

Desired output of circular iteration: 
(1,2) 
(2,3) 
(3,4) 
(4,1) 

回答

4

這裏是圓形的情況下

for i = 1, #t do 
    local a,b 
    a = t[i] 
    if i == #t then b = t[1] else b = t[i+1] end 
    print(a,b) 
end 

非圓形:

for i = 1, #t-1 do 
    print(t[i],t[i+1]) 
end 

對於發燒友輸出使用print(string.format("(%d,%d)",x,y)

6

爲圓形情況下

另一種解決方案
1

這兩種情況都沒有特殊情況如何?

function print_pair(x, y) 
    local s = string.format("(%d, %d)", x, y) 
    print(s) 
end 

function print_pairs(t) 
    for i = 1, #t - 1 do 
     print_pair(t[i], t[i + 1]) 
    end 
end 

function print_pairs_circular(t) 
    print_pairs(t) 
    print_pair(t[#t], t[1]) 
end