How to use Lua Programming to check if a file exists?


Lua provides us with different functions and methods that we can use when we want to work with files. These methods or functions do different operations, like from opening a file, to closing a file, to opening a file with a specific mode also.

While many of these functions that Lua provides to work with files, two of them are more subtle to use and work with.

In this article we will explore these two approaches, where in the first approach we will simply open a file by passing the name of the file and the mode in which we want to open the file, and then we will print whether the file is present or not.

It should be noted that if the file was found by Lua, then only the address will be printed where the file is located, but if no file was found, then nil will be printed.

Example

Consider the example shown below −

print(io.open("sample.txt", "r"))

If we have a file named “sample.txt” present inside the same directory where the above Lua file is present, then we will get the following output to the terminal.

Output

file (0x22ac2b0)

If we don’t have a file named the above Lua file is present, “sample.txt” present inside the same directory where then we will get the following output to the terminal.

Output

nil sample.txt: No such file or directory2

A better way to write this code is to make a separate function to check whether the file is present or not, and in that function we can also close the file once we open it and can also return true if we encounter the file, or false if we don’t.

Example

Consider the example shown below −

 Live Demo

function file_exists(name)
   local f=io.open(name,"r")
   if f~=nil then io.close(f) return true else return false end
end
ans = file_exists("sample.txt")
print(ans)

Output

false

Updated on: 20-Jul-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements