无缘无故获得零值

问题描述 投票:0回答:1

我很难找出问题所在:我应该使用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个回答
0
投票

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

请注意,在检查“行”是否为零之前,请先输入print("first line is: "..line)

© www.soinside.com 2019 - 2024. All rights reserved.