Lua - Reading Files
Lua provides I/O library to read and manipulate files. We can open a file in read mode using following ways−
Simple Model
content = io.read ([, mode])
Where−
mode− an optional mode specifying the access mode of the file.
This method reads the first line of the file if mode is not specified. Otherwise, as per mode, the content is returned.
Before reading a file, it should be opened using following syntax:
-- Opens a file specified by fileName in read mode file = io.open(fileName, "r") -- sets the default input file io.input(file)
Complete Model
content = file.read ([, mode])
Where−
file− file handle returned by io.open().
mode− an optional mode specifying the access mode of the file.
This method reads the first line of the file if mode is not specified. Otherwise, as per mode, the content is returned.
Before reading a file, it should be opened using following syntax:
-- Opens a file specified by fileName in read mode file = io.open(fileName, "r")
Read Modes
Let's explore the various options to read content of a file using read() method:
| Sr.No. | Mode & Description |
|---|---|
| 1 | "*n"/"*number" Reads from the current file position and returns a number if exists at the file position or returns nil. |
| 2 | "*a"/"*all" Returns all the contents of file from the current file position. |
| 3 | "*l"/"*lines" Reads the line from the current file position, and moves file position to next line. |
| 4 | number Reads number of bytes specified in the function. |
we will use a sample file example.txt as shown below−
example.txt
Welcome to tutorialspoint.com Simply Easy Learning
Example - Read File line by Line
Let us now see how to read a file line by line.
main.lua
-- read a file content and returns the same
function readFile()
-- Opens a file in read
f = io.open("example.txt","r")
-- read first line
print(f:read())
-- read next line
print(f:read())
-- close the file handle
f:close()
-- return the contents
return contents
end
-- read the file
readFile()
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning
Example - Read File All at once
Let us now see how to read file contents in single call.
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 content
print(f:read("*a"))
-- close the file handle
f:close()
-- return the contents
return contents
end
-- read the file
readFile()
Output
When the above code is built and executed, it produces the following result −
Welcome to tutorialspoint.com Simply Easy Learning