3

luaのテーブル要素のペアを反復処理する方法は?円形および非円形の反復verペアの副作用のない方法を実現したいと思います。

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 に答える