遇到不明原因的 nil 值

我正在努力找出问题所在: 我应该使用 lua 从文本文件中读取行,并打印包含字符串“login”或“logout”的行 - 如果我到达文件末尾,则打印(“到达文件末尾”)。 由于某种原因,第一行(我想是)收到了 nil 值,因此我陷入困境.... 我会提到我正在使用 cmd从脚本所在的确切文件夹运行 lua 代码

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

while true do
    print("第一行是:"..line)
    if line == nil then
        print("到达文件末尾")
        break
    else
        if string.match(line, "login") then
            print("到达登录行:" .. line)
        elseif string.match(line, "logout")  then
            print("到达注销行:" .. line)
        end
    end
    line = file:read()
end
file:close()

日志文件:
13:20:20 [111] 登录
13:22:00 [111] 存款
13:22:01 [111] 电话
13:50:50 [111] 注销
(写在文本文件中)。

任何帮助将不胜感激...

点赞
用户5113346
用户5113346

最简单的修复方法是: 将while true do替换为while line do

请记住,在检查'line'是否为空之前,您有print("first line is: "..line)

实际上,您不希望在循环内使用print("first line is: "..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()
2019-11-10 11:54:46
用户4240261
用户4240261

就像 @Alundaio 所说,即使是 nil,你也打印每行作为“第一行”。 while line do 将更整洁。

但更重要的是,你从未匹配过 log-inlog-out,因为你搜索的是没有连字号的 loginlogout

你可以考虑选择性匹配连字符:log%-?inlog%-?out,根据 @Alundaio 建议使用特殊字符文字语法,或使用字符类语法中的 log[-]?inlog[-]?out

根据 @Alundaio 的答案,如果您想假设破折号始终存在,请使用 log%-in / log%-outlog[-]in / log[-]out

2019-11-10 11:59:04
用户2858170
用户2858170

你不需要 while 循环来读取文件的每一行。

你可以简单地使用 泛型 for 循环file:lines 方法。

在该循环中,line 永远不会为 nil。因此你不需要手动检查。

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()
2019-11-11 07:53:15