Lua - Checking if File is Writable
It is always good to check if a file is writable before reading a file and then handle the situation gracefully. To check if file is writable or not, we can check the io.open() status.
Syntax - io.open()
f = io.open(filename, [mode])
Where−
filename− path of the file along with file name to be opened.
mode− optional flag like r for read, w for write, a for append and so on.
f represents the file handle returned by io.open() method. In case of successful open operation, f is not nil. Following examples show the use cases of checking a file is writable or not.
We're making a check on example.txt which is present in the current directory and is writable where lua program is running.
main.lua
-- check if file is writable
function writable(filename)
local isWritable = true
-- Opens a file in write mode
f = io.open(filename, "w")
-- if file is not writable, f will be nil
if not f then
isWritable = false
else
-- close the file
f:close()
end
-- return status
return isWritable
end
-- check if file is writable
if writable("example.txt") then
print("example.txt is writable.")
else
print("example.txt is not writable.")
end
Output
When we run the above program, we will get the following output−
example.txt is writable.
Example - Checking if file is not writable
We're making a check on example1.txt which is present in the current directory and is readonly where lua program is running.
main.lua
-- check if file is writable
function writable(filename)
local isWritable = true
-- Opens a file in write mode
f = io.open(filename, "w")
-- if file is not writable, f will be nil
if not f then
isWritable = false
else
-- close the file
f:close()
end
-- return status
return isWritable
end
-- check if file is not writable
if not writable("example1.txt") then
print("example1.txt is not writable.")
else
print("example1.txt is writable.")
end
Output
When we run the above program, we will get the following output−
example1.txt is not writable.