0
votes

i am having a hard time trying to figure out what is wrong: i am supposed to read lines from a text file using lua, and print said lines who contain the strings "login" or "logout" - and if i reach the end of the file, to print ("reached end of file"). for some reason the first line (i think) is receiving a nil value, and therefore i am stuck.... i will mention i am running the lua code using cmd from the exact folder the script is written

lua code:
file = io.open("dummy_log.txt", "r")
line = file:read() 

while true do 
    print("first line is: "..line)
    if line == nil then
        print("reached end of file")
        break
    else 
        if string.match(line, "login") then
            print("reached login line: " .. line)
        elseif string.match(line, "logout")  then
            print("reached logout line: " .. line)
        end
    end
    line = file:read()
end
file:close()

log file:
13:20:20 [111] log-in
13:22:00 [111] deposit
13:22:01 [111] phone-call
13:50:50 [111] log-out
(is written in a text file).

help will be appreciated...

3

3 Answers

1
votes

The simplest fix is: Replace: while true do With: while line do

Keep in mind you have print("first line is: "..line) before you check if 'line' is nil.

You actually don't want print("first line is: "..line) inside the loop as it will claim every line is the first line.

file = io.open("dummy_log.txt", "r")
line = file:read() 
print("first line is: "..line)

while line do 
    if string.find(line, "log%-in") then
        print("reached login line: " .. line)
    elseif string.find(line, "log%-out")  then
        print("reached logout line: " .. line)
    end
    line = file:read()
end
file:close()
1
votes

You don't need a while loop to read lines of a file.

You can simply use a generic for loop with file:lines

Within that loop line will never be nil. So you don't have to check it manually.

local file = io.open("dummy_log.txt", "r")

for line in file:lines() do
  if line:find("log%-in") then
    print("reached login line: " .. line)
  elseif line:find("log%-out") then
    print("reached logout line: " .. line)
  end
end
print("end of file")
file:close()
0
votes

Like @Alundaio said, you print every line as "first line", even if it is nil. while line do will be neater.

But most importantly, you never match the log-in and log-out because you are searching for login and logout (without the dash).

You may want to consider matching dashes optionally: log%-?in, log%-?out as per @Alundaio's suggestion to use the special-character literal syntax, or log[-]?in, log[-]?out to use character-class syntax on the dash.

As per @Alundaio's answer, use log%-in/log%-out or log[-]in/log[-]out if you want to assume the dashes are always there.