2

I'm trying to parse a txt file which is in the format of host-name IP mac-address in Lua. All three separated with spaces, to try and then store it into a table using Lua.

I've tried doing this using :match function but can't see to get it to work.

function parse_input_from_file()
  array ={}
  file = io.open("test.txt","r")
  for line in file:lines() do
    local hostname, ip, mac = line:match("(%S+):(%S+):(%S+)")
    local client = {hostname, ip, mac}
  table.insert(array, client)
  print(array[1])
  end
end

It keeps on printing the location in memory of where each key/value is stored (I think).

I'm sure this is a relatively easy fix but I can't seem to see it.

1
  • you say spaces is a separator, then: line:match("(.+)%s+(.+)%s+(.+)") Commented Mar 31, 2019 at 7:32

2 Answers 2

2

If hostname, ip and mac are separated by space your pattern may not use colons. I added a few changes to store the captures in the client table.

function parse_input_from_file()
  local clients ={}
  local file = io.open("test.txt","r")
  for line in file:lines() do
    local client = {}
    client.hostname, client.ip, client.mac = line:match("(%S+) (%S+) (%S+)")
    table.insert(clients, client)
  end
  return clients
end

for i,client in ipairs(parse_input_from_file()) do
   print(string.format("Client %d: %q %s %s", i, client.hostname, client.ip, client.mac))
end

Alternatively:

local client = table.unpack(line:match("(%S+) (%S+) (%S+)"))

then hostname is client[1] which is not very intuitive.

Sign up to request clarification or add additional context in comments.

Comments

1

No colon in the regex:

local sampleLine = "localhost 127.0.0.1 mac123"
local hostname, ip, mac = sampleLine:match("(%S+) (%S+) (%S+)")
print(hostname, ip, mac) -- localhost 127.0.0.1 mac123

2 Comments

That's brilliant - I knew it was something as trivial as this. Do you know how I'm able to store this in an array/table. So if I had two sample Lines, it could store a list and within the list the table?
@Syn create a local table for each line local tab = {} tab.hostName, tab.ip, tab.mac = sampleLinie:match("(%S+) (%S+) (%S+)") and put them into another table. if you don't care about string keys you can also use local tab = table.pack(sampleLinie:match("(%S+) (%S+) (%S+)")) of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.