3

如何迭代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

3 回答 3

6

圆形外壳的另一种解决方案

   local n=#t
    for i=1,n do 
      print(t[i],t[i%n+1]) 
    end
于 2011-10-24T21:05:30.107 回答
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)

于 2011-10-24T17:40:25.923 回答
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
于 2015-08-03T10:13:17.143 回答