Oti Na Nai
Oti Na Nai

Reputation: 1407

Lua check if a file is open

I use:

file = io.open(path)

to open a file specified by the path. Now, after some actions, I would use file:close() to close the file but there are some times that I didn't even open a file to close it after. How can I check whether a file has been open or not?

Upvotes: 1

Views: 2948

Answers (2)

ryanpattison
ryanpattison

Reputation: 6251

hjpotter92 suggestion works, the condition is not always false:

> 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 you follow this pattern then closing only an open file is easy:

   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

A file is open if and only if it exists (not nil).

Upvotes: 2

Jpc133
Jpc133

Reputation: 28

It is very hard using standard Lua calls to check if a file is open, however if it is just one script accessing the file You could set a variable to True when you open the file and check for it before closing it.

You may find this page helpful: Lua check if a file is open or not

Upvotes: 1

Related Questions