Lua 检查文件是否打开

Lua check if a file is open

我使用:

file = io.open(path)

打开路径指定的文件。现在,经过一些操作后,我会使用 file:close() 来关闭文件,但有时我什至没有打开文件就关闭它。如何查看文件是否已打开?

很难使用标准 Lua 调用来检查文件是否打开,但是如果只有一个脚本访问文件 您可以在打开文件并检查文件时将变量设置为 True关闭它之前。

您可能会发现此页面有帮助: Lua check if a file is open or not

hjpotter92 建议有效,条件并不总是假的:

> if file then print("File was opened") else print("What File?") end
What File?
> file = io.open("file.txt")
> if file then print("File was opened") else print("What File?") end
File was opened
> file:close()
> file = nil -- assign to nil after closing the file.
> if file then print("File was opened") else print("What File?") end
What File?
> 

如果您遵循此模式,则仅关闭一个打开的文件很容易:

   if math.random() < .5 then
      file = open("file.txt") -- maybe it opened
   end

   if file then -- close only if opened
     file:close()
     file = nil
   end

文件打开当且仅当它存在(不是零)。