为什么即使文件中只有0它仍然执行?

这应该检查文件中是否有零,如果不是零,则应执行代码。 但即使它只有0,它仍会执行代码。

f = io.open("timesave.txt", "r")
if (f ~= 0) then
    io.input(f)
    resultstart = f:read("*line")
    resultstop = f:read("*line")
    f:close()
end

原文链接 https://stackoverflow.com/questions/70272041

点赞
stackoverflow用户2858170
stackoverflow用户2858170

io.open("timesave.txt", "r") 函数如果成功则返回文件句柄,否则返回 nil。

来自:https://www.lua.org/manual/5.4/manual.html#pdf-io.open

io.open (filename [, mode])

此函数以指定的模式打开文件, 并返回一个新的文件句柄. ...

你不能使用 io.open 来检查一个文件是否只含有 0。

为了实现这一点,你需要打开文件,读取并检查其内容。

-- 以读取方式打开文件 
local f = io.open("timesave.txt", "rb")
-- 检查文件是否已打开 
if not f then print("failed to open file") return end
-- 读取并检查文件中是否只有一个0 
if f:read("a") == "\0" then print("file only contains \\0") end
f:close()
2021-12-08 09:01:21