Lua检查文件是否打开

Lua检查文件是否打开,lua,Lua,我使用: 打开由路径指定的文件。现在,在完成一些操作后,我将使用file:close()关闭文件,但有时我甚至没有打开一个文件来关闭它。如何检查文件是否已打开?使用标准Lua调用来检查文件是否已打开是非常困难的,但是,如果只是一个脚本访问文件,则可以在打开文件时将变量设置为True,并在关闭文件之前对其进行检查 您可能会发现此页面很有帮助: hjpotter92建议有效,条件并不总是错误的: file = io.open(path) 如果遵循此模式,则只关闭打开的文件很容易: > if

我使用:


打开由路径指定的文件。现在,在完成一些操作后,我将使用
file:close()
关闭文件,但有时我甚至没有打开一个文件来关闭它。如何检查文件是否已打开?

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

您可能会发现此页面很有帮助:

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

file = io.open(path)
如果遵循此模式,则只关闭打开的文件很容易:

> 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?
> 
如果math.random()<.5,则
file=open(“file.txt”)--可能它已打开
结束
if file then--仅在打开时关闭
文件:close()
file=nil
结束

当且仅当文件存在时才打开该文件(非空)。

此条件始终为false=/check out
io.type
function。但这个只检查描述符,而不是文件,它本身并没有将nil赋值给文件,这是因为它总是向我显示false。谢谢你的回答:)
   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