Lua - Modes for File Access
Lua provides I/O library to read and manipulate files. There are two models, a Simple Model which uses io module and Complete Model which use file handle returned by io module methods. We can open a file using following syntax−
file = io.open (filename [, mode])
Where−
filename− name of file to be opened.
mode− an optional mode specifying the access mode of the file.
This method opens the file as per provided mode and returns a file handle which then can be used to perform further operations on the file.
Access Modes
The various file modes are listed in the following table.
| Sr.No. | Mode & Description |
|---|---|
| 1 | "r" Read-only mode and is the default mode where an existing file is opened. |
| 2 | "w" Write enabled mode that overwrites the existing file or creates a new file. |
| 3 | "a" Append mode that opens an existing file or creates a new file for appending. |
| 4 | "r+" Read and write mode for an existing file. |
| 5 | "w+" All existing data is removed if file exists or new file is created with read write permissions. |
| 6 | "a+" Append mode with read mode enabled that opens an existing file or creates a new file. |
Example - Opening File in Write Mode
Let us now see how to open a file in write mode first.
main.lua
-- write a file content
function writeFile()
-- Opens a file in write mode,
-- create file if not present
-- overwrite content of file if present
f = io.open("example.txt","w")
-- write the contents
f:write("Welcome to tutorialspoint.com", "\n")
f:write("Simply Easy Learning", "\n")
-- close the file handle
f:close()
end
-- write the file
writeFile()
print("Content written to the file successfully.")
Output
When the above code is built and executed, it produces the following result −
Content written to the file successfully.
Example - Opening File in Read Mode
Let us now see how to open a file in read mode.
main.lua
-- read a file content and returns the same
function readFile()
-- Opens a file in read
f = io.open("example.txt","r")
-- read all the contents
contents = f:read("*all")
-- close the file handle
f:close()
-- return the contents
return contents
end
-- read the file and get the contents
contents = readFile()
-- print the contents
print(contents)
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning