IO 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

io.input(filename)

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

io.output(filename)

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

IO.WRITE

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 ) )

IO.READ

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:

io.stdin:read("a")

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

io.stdout:write()

To print error we can use

io.stderr:write()

Note the following:

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

local temp = io.input()
io.input("filename")
io.input:read()
io.read() -- alternative
io.input:close()
io.input(temp) -- restore original

Data files

--- data.lua

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

Entry{
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

dofile("data.lua")
for name in pairs(authors) do print(name) end

Serialization

Share the page with