3

I'm rather new to Lua. For each match of gmatch, I would like to put the capture group results into an array.

The idea is so I get all the capture groups for each match, as an array, so I can do operations on this array, e.g. convert each capture group to an int.

How would I change the following, so it prints 3 2 1?

function split_ipv4(str)
    for parts in str:gmatch('(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?)%.(%d%d?%d?), ') do
       print(parts[4])
    end
end

split_ipv4('192.168.0.3, 192.168.0.2, 192.168.0.1')

Changing parts to p1, p2, p3, p4 and printing p4 works, but is there a way of not creating a variable for each group?

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
simonzack
  • 19,729
  • 13
  • 73
  • 118

1 Answers1

3

The most simple way is to change parts to p1, p2, p3, p4
But in case of variable-phobia:

function split_ipv4(str)
   for addr in str:gmatch'%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?' do
      local parts = {addr:match'(%d+)%.(%d+)%.(%d+)%.(%d+)'}
      print(parts[4])
    end
end

split_ipv4('192.168.0.3, 192.168.0.2, 192.168.0.1')
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64