Lua - Open File



Lua provides I/O library to read and manipulate files. In this article, we'll checkout the ways to open a file.

we will use a sample file example.txt as shown below−

example.txt

Welcome to tutorialspoint.com
Simply Easy Learning

Complete Model - Open File In Read Mode

Let us now see how to open a file in read mode first.

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

Here we've used following code

-- Opens a file in read
f = io.open("example.txt","r")

We can open a file without r mode as well as shown below−

-- Opens a file in read
f = io.open("example.txt")

io.open() function opens the file and returns a file handle. Using file handle we can read the content of the file, write content to the file which will clear the existing content and write the new one or append content over existing one.

This mode, where we're using a file handle to perform File I/O is called Complete Model. There is one Simple Model as well where we're not using the file handle.

Simple Model - Open File In Read Mode

In simple mode, we use io.input() to set as a default input file or io.output() to set as default output file. Let's re-write the above example using simple model.

main.lua

-- read a file content and returns the same
function readFile()
   -- Opens a file in read
   f = io.open("example.txt","r")
   -- sets the default input file as test.lua
   io.input(f)
   -- read all the contents
   contents = io.read("*all")
   -- close the file handle
   io.close(f)
   -- 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
Here we've used io.read(), io.close() methods instead of file handle specific methods like file:read() and file:close() methods.
Advertisements