Search code examples
loopslualua-table

How to iterate over pairs of elements in table in lua


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)

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)