Lua 检查文件是否已打开

我使用:

file = io.open(path)

打开一个指定路径的文件。现在,在执行一些操作后,我会使用 file:close() 来关闭文件,但有时我甚至没有打开文件,就想要关闭它。我该如何检查文件是否已被打开?

点赞
用户4627435
用户4627435

使用标准的 Lua 调用来检查文件是否已经打开非常困难,但是如果只有一个脚本访问该文件,可以在打开文件时将一个变量设置为 True,在关闭文件之前进行检查。

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

2015-03-04 23:48:34
用户2726734
用户2726734

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

> if file then print("文件已经被打开") else print("哪个文件?") end
哪个文件?
> file = io.open("file.txt")
> if file then print("文件已经被打开") else print("哪个文件?") end
文件已经被打开
> file:close()
> file = nil -- 关闭文件后赋值为nil
> if file then print("文件已经被打开") else print("哪个文件?") end
哪个文件?
>

如果按照这个模式,则仅关闭已打开文件变得容易:

   if math.random() < .5 then
      file = open("file.txt") -- 可能已经打开
   end

   if file then -- 仅在已打开情况下关闭
     file:close()
     file = nil
   end

当且仅当文件存在(不为nil)时,该文件是打开的。

2015-03-05 00:56:56