Reputation: 35
I'm reasonably new to Lua although I have used other languages which are similar. So far I've spent 8 hours to no avail trying to parse a large text file.
The file in question looks something like this: (but thousands of lines long)
A|KLAX|LOS ANGELES INTERNATIONAL|33942522|-118407161|125
I've got the user to enter the KLAX variable, but my goal is to get out this part of the line in question WITHOUT using tables: 33942522|-118407161
E.g.
APTDEP_DATA = 33942522|-118407161
Or even get a whole line out of the .txt file as a string?
E.g.
APTDEP_DATA = A|KLAX|LOS ANGELES INTERNATIONAL|33942522|-118407161|125
Thanks a heap in advance. After 8 hours, it would be great to know whether what I'm trying to do is even possible. (Every tutorial I see is parsing data into tables)
I've tried a lot of things to this effect:
THE NZAA is also a code I was trying to find. So don't get confused with KLAX thing. I was just trying to get a result.
(I couldn't get the code to show properly, sorry about the link)
Upvotes: 0
Views: 561
Reputation: 20858
From looking at your example snippet, the problem is coming from your usage of:
AP_LAT = string.match(file, "A|NZAA")
Pattern matching is performed on a string value, not a file
handle. More appropriate would be:
AP_LAT = string.match(line, "A|NZAA")
The following processes your input file a line at a time and also parses it to its respective fields:
file = assert(io.open("Airports.txt", "r"))
for line in file:lines() do
local fields = { line:match "(%w+)|(%w+)|([%w ]+)|([%d-]+)|([%d-]+)|([%d-]+)" }
-- do something useful with it
print(fields[4], fields[5]) -- the 2 numeric fields you're interested in
end
file:close()
If you're adamant about no tables, you can just punt the matches into variables like this:
local first, second, third, etc = line:match "(%w+)|(%w+)|([%w ]+)|([%d-]+)|([%d-]+)|([%d-]+)"
Note: Feel free to modify/refine the pattern to suit your needs. This is just an example to illustrate the idea.
Upvotes: 4
Reputation: 122483
To read lines from a file, use io.lines
:
for line in io.lines(filename) do
--do some processing
end
To get specific part from the line, use pattern matching. I'm not sure what you are trying to get from the question.
Upvotes: 0