【问题标题】:getting nil value for no apparent reason无缘无故地获得零值
【发布时间】:2020-03-06 08:48:54
【问题描述】:

我很难找出问题所在: 我应该使用lua从文本文件中读取行,并打印包含字符串“login”或“logout”的行 - 如果我到达文件末尾,则打印(“到达文件末尾”)。 出于某种原因,第一行(我认为)正在接收 nil 值,因此我被卡住了.... 我会提到我正在使用 cmd 从编写脚本的确切文件夹中运行 lua 代码

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).

我们将不胜感激...

【问题讨论】:

    标签: lua


    【解决方案1】:

    最简单的解决方法是: 替换:while true do 与:while line do

    在检查 'line' 是否为 nil 之前,请记住您有 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()
    

    【讨论】:

      【解决方案2】:

      像@Alundaio said 一样,您将每一行都打印为“第一行”,即使它是nilwhile line do 会更整洁。

      但最重要的是,您永远不会匹配 log-inlog-out,因为您正在搜索 loginlogout(没有破折号)。

      您可能需要考虑选择匹配破折号:log%-?inlog%-?out 根据@Alundaio 的建议使用特殊字符文字语法,或log[-]?inlog[-]?out 在破折号上使用字符类语法.

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

      【讨论】:

        【解决方案3】:

        您不需要 while 循环来读取文件的行。

        您可以简单地将generic for loopfile: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()
        

        【讨论】:

          猜你喜欢
          • 2012-05-12
          • 2021-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-10
          • 2017-04-11
          • 1970-01-01
          • 2023-04-03
          相关资源
          最近更新 更多