Question

How to iterate over pairs of table elements in lua? I would like to achieve a side-effect free way of circular and non-circular iterating ver pairs.

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)
Was it helpful?

Solution

Here's the circular case

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

Non circular:

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

For fancier output use print(string.format("(%d,%d)",x,y)

OTHER TIPS

Another solution for the circular case

   local n=#t
    for i=1,n do 
      print(t[i],t[i%n+1]) 
    end

How about having no special case for both cases?

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top