如何在lua中迭代表中的元素对

如何在Lua中迭代表元素的一对?我想实现一种无副作用的循环和非循环迭代 ver 对。

我有像这样的表格:
t={1,2,3,4}

非循环迭代的期望输出:
(1,2)
(2,3)
(3,4)

循环迭代的期望输出:
(1,2)
(2,3)
(3,4)
(4,1)

原文链接 https://stackoverflow.com/questions/7879156

点赞
stackoverflow用户33252
stackoverflow用户33252

以下是循环案例:

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-24 17:40:25
stackoverflow用户107090
stackoverflow用户107090

另一种解决循环情况的方法

  local n = #t
  for i = 1, n do
    print(t[i], t[i%n + 1])
  end 
2011-10-24 21:05:30
stackoverflow用户183120
stackoverflow用户183120

如果两种情况都不设特殊情况怎么样?

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-03 10:13:17