The built-in io module lets a program talk to the outside world. It allows you to open files, reading and writing their contents, and gives access to the standard streams of the process. It is a standard module, and like any other it is brought in with import:

import io

The module has two kinds of members. The functions io.open and io.popen creates files, and the attributes io.stdin, io.stdout and io.stderr are the three files that every program already has. A file is an instance of the class io.File, and everything we do with one is done through its methods.

Files

Opening and Closing

The function io.open takes the path of a file and, optionally, a mode string, and returns a file:

var f = io.open("notes.txt")            // for reading
var g = io.open("report.txt", "w")      // for writing

The mode is the same as the one used by C’s fopen. The most common ones are:

ModeMeaning
"r"Read an existing file. This is the default.
"w"Write, creating the file or emptying it if it exists.
"a"Write at the end of the file, creating it if needed.
"r+"Read and write an existing file

Adding b to a mode, as in rb, opens the file in binary mode on systems that distinguish between text and binary files. Since strings can hold arbitrary bytes, this is how binary data is read and written.

If the file cannot be opened, for example because it does not exist, io.open raises an error.

When a program has finished with a file, it should call close:

f.close()

A closed file cannot be used anymore, nor can it be closed again, and trying to read from or write to it raises an error. A file that is no longer referenced is closed by the garbage collector, but nothing says when that will exactly happen, and data written to the file may sit in memory until then.

It is good practice to close files explicitly. It is especially important as file handles are limited by a certain number by the OS, and exceeding the limit will block and consequent IO file openings.

Writing

The write method writes its arguments to the file, in order. It accepts any number of strings and numbers; numbers are converted to text. It adds nothing of its own; in particular, there is no newline unless we write one.

var out = io.open("squares.txt", "w")

for var i in 1..6
{
    out.write(i, " squared is ", i * i, "\n")
}

out.close()

Values of other types must be converted with tostring first.

Reading

The read method returns the contents of the file as a string. Without arguments it reads everything from the current position to the end of the file:

var f = io.open("notes.txt")
var text = f.read()
f.close()

With a number, it reads at most that many bytes. The result is shorter than requested when the end of the file is reached, and empty when nothing is left:

var header = f.read(16)     // the first 16 bytes

To read a text file one line at a time we can use readline. It returns the next line without its terminating newline, and nil when there are no more lines. An empty line is the empty string, so it can be told apart from the end of the file:

var line = f.readline()
while line != nil
{
    print(line)
    line = f.readline()
}

Iterating over Lines

A file can be used directly in a for loop, which produces its lines one by one, just like repeated calls to readline. This is the usual way of processing a text file:

var f = io.open("notes.txt")

for var line in f
{
    print(line)
}

f.close()

Pipes

The function io.popen runs a command and returns a file connected to it. With the default mode "r", reading from the file gives us what the command prints:

var p = io.popen("echo hello")
print(p.read())

With "w", whatever is written to the file is sent to the command as input. Not every platform supports this, and io.popen just raises an error where it is not available.

Standard Streams

Every process starts with three streams, and the module provides them as files:

FileStream
io.stdinstandard input
io.stdoutstandard output
io.stderrstandard error

They have all the methods described above. The standard streams cannot be closed, so calling close on any of them raises an error.

Writing to io.stdout is what print does, except that print adds the final newline for us, and stringifies all values. Error messages are customarily sent to io.stderr, so that they stay visible when the output of the program is redirected:

io.stdout.write("processing...\n")
io.stderr.write("warning: no input given\n")

Reading from io.stdin is the way to receive input from the user, or from another program through pipe, and it’s equivalent to input:

io.stdout.write("What is your name? ")
io.stdout.flush()

var name = io.stdin.readline()
print("Hello, ${name}!")

The call to flush in this example is explained in the next section. Since io.stdin is a file, a for loop over it handles the lines of the input until it ends:

var count = 0
for var line in io.stdin
{
    count += 1
}
print("${count} lines")

Buffers and Seeking

Buffering

Reading and writing a file one small piece at a time would be slow, so the system collects data in an in-memory buffer and transfers it in larger blocks. This has a visible consequence; what we write may not reach its destination immediately. The flush method forces everything written so far to be sent out. We used it above to make sure the prompt appears before the program waits for an answer.

How buffering is done can be changed with setvbuf, which takes a mode and, optionally, a buffer size in bytes. The mode is one of the strings "full", "line" and "no""

io.stdout.setvbuf("no")         // write everything immediately
log.setvbuf("line")             // flush at each newline

Closing a file also flushes it.

Seeking

Each file has a current position, a cursor which moves forward as we read or write. The seek method moves it explicitly. It takes the point from which to count, as one of the strings "set" (start of the file), "cur" (current position) and "end" (end of the file), followed by an offset in bytes, which defaults to zero. The point defaults to "cur". It returns the new position, counted from the start of the file:

var f = io.open("data.bin", "rb")

var size = f.seek("end")        // go to the end: the position is the size
f.seek("set")                   // back to the start

f.seek("set", 8)                // skip the first 8 bytes
var chunk = f.read(4)

print(f.seek())                 // 12, calling seek changes nothing here

Seeking is the way to read a file twice, to jump to a known offset in a binary file, or, when a file is opened for both reading and writing, to move between the two.

An Example

The following program copies a text file and puts a line number in from of each line. It reads the input with a for loop, writes the output with write, and closes both files at the end:

import io

var input = io.open("notes.txt")
var output = io.open("numbered.txt", "w")

var n = 1
for var line in input
{
    output.write(n, ": ", line, "\n")
    n += 1
}

input.close()
output.close()

print("copied ${n - 1} lines")

If notes.txt contains the lines buy tea and drink tea, then numbered.txt will contain:

1: buy tea
2: drink tea

The program prints copied 2 lines.