我很难找出问题出在哪里:我应该使用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).我们会很感激的..。
发布于 2019-11-10 19:54:47
最简单的修复方法是:用:while line do替换:while true do
请记住,在检查‘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-11 15:53:15
您不需要使用while循环来读取文件的各行。
您可以简单地在file:lines中使用generic for loop
在这个循环中,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-10 19:59:04
就像@Alundaio said一样,你把每一行都打印成“第一行”,即使它是nil。while line do将会更整洁。
但最重要的是,您永远不会匹配log-in和log-out,因为您搜索的是login和logout (没有破折号)。
您可能希望考虑可选地匹配破折号:按照@Alundaio的建议使用特殊字符文字语法的log%-?in、log%-?out,或者在破折号上使用字符类语法的log[-]?in、log[-]?out。
根据@Alundaio的回答,如果您想假设破折号始终存在,请使用log%-in/log%-out或log[-]in/log[-]out。
https://stackoverflow.com/questions/58788260
复制相似问题