Loops in Lua

Share the page with

IO in Lua

In this post I will describe my understanding of input and output operations in Lua. In any programming language we have two types of input or output devices (sometimes they are also called buffer); standard devices and user specified devices.

Changing the current input stream


will change the current input stream to the external file named filename.


will change the current output stream to the external file named filename


The function io.write writes to the output stream.

As a rule we should avoid using print() function, and always use io.write() function as it gives us a full control over the output.

Example of io.write

io.write( string.format( "3.0/2.0 = %.4f \n", 3.0/2.0 ) )


The function io.read() reads from the input stream.

Also see, io.lines()

Opening a file

To open a file we use io.open(filename, mode). Where we provide filename and mode (read, write). For reading an existing file we use mode=r, and for writing to a file we use mode=w. We use mode=a for appending to an existing file. A good way to open a file is following.

local f = assert( io.open( filename, mode ) )

To read this file we use the read method, which can be access by : as shown below.

local t = f:read("a")

To close the file we use close method.

To read from the standard input we can use following:


To write to the standard output we can use the following:


To print error we can use


Note the following:

We can change the io.input or io.output temporally using

local temp = io.input()
io.read() -- alternative
io.input(temp) -- restore original

Data files

--- data.lua

author = "Donald E. Knuth",
title = "Literate Programming",
publisher = "CSLI",
year = 1992

author = "Jon Bentley",
title = "More Programming Pearls",
year = 1990,
publisher = "Addison-Wesley",
local authors = {}
-- a set to collect authors
function Entry(b) authors[b.author] = true end

for name in pairs(authors) do print(name) end


Share the page with