Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 10: Files, the operating system, and data

Objectives: LO-10.1, LO-10.2, LO-10.3
Prerequisites: the Module 10 reading and Lab 9
Time: about 2 hours

You will write a helper that always closes its file, a CSV parser and writer that handle quoted fields, a reader that turns a CSV file into records and reports bad lines, a serializer whose output reads back safely, and a shell quoter and a date calculator. As in the earlier labs, each check cell prints passed or fails with a message, and the checks fail until you finish their exercise. Section 5 runs commands through the shell, so it needs Linux or macOS.

Setup

The lab writes its files into its scratch folder, which Git ignores. The second cell prints the Lua version, which should be Lua 5.4.

1. Closing on every path

Exercise L10.1 (LO-10.1, ★★, about 20 minutes)

Write with_file(path, mode, fn). It opens path in mode; if that fails, it returns nil and io.open’s message. Otherwise it calls fn(file) and returns all of fn’s results. The file must be closed when with_file returns, and also when fn raises an error, which with_file lets through to its caller. Don’t call file:close() yourself.

Hint

Declare the handle with <close> after checking that io.open succeeded, and return fn(file) from the same scope.

2. CSV

Exercise L10.2 (LO-10.3, ★★★, about 30 minutes)

Write two functions for lines of CSV without line breaks inside fields:

  • csv_split(line) returns a list of the fields of line. A field in double quotes may contain commas, and a doubled double quote inside it stands for one double quote; the quotes around a field aren’t part of its value. An empty line has one empty field.

  • csv_join(fields) returns the line for a list of strings, putting a field in double quotes, with its double quotes doubled, only if it contains a comma or a double quote.

LineFields
a,b,ca, b, c
Ada,"London, UK",36Ada, London, UK, 36
"said ""hi""",xsaid "hi", x
,,three empty fields
Hint 1

Walk the line one character at a time with a flag that says whether you are inside quotes. A comma ends a field only outside quotes.

Hint 2

Inside quotes, a " followed by another " is one quote character, so skip ahead two characters; a " followed by anything else ends the quoted part.

3. From a file to records

The next cell writes a small CSV file whose first line names the columns. Line 4 has a field missing.

Exercise L10.3 (LO-10.1, LO-10.3, ★★, about 20 minutes)

Write read_records(path), which reads a CSV file whose first line names the columns, and returns a list of records, one table per line, keyed by the column names. Use your csv_split. A file is data from outside the program, so report problems by returning nil and a message, not by raising an error: io.open’s message if the file can’t be opened, or "line <n>: expected <k> fields, got <m>" for the first line with the wrong number of fields, counting the header as line 1. Close the file on every path.

4. Writing Lua values, and reading them back

Exercise L10.4 (LO-10.3, ★★, about 25 minutes)

Write two functions:

  • serialize(value) returns a Lua chunk, return …, that rebuilds value: a string, a number, a boolean, or a table whose keys are strings or numbers and whose values are any of these, nested to any depth. Write every string and number with %q, and each table’s keys in sorted order, numbers before strings, so the same value always gives the same text.

  • deserialize(text) runs such a chunk with load in text mode and an empty environment, and returns the value; if the chunk doesn’t compile, or raises an error, it returns nil and the message.

Hint

Write a recursive helper that returns the literal for one value, and builds a table’s literal as {[key]=value,...} from its sorted keys. Sort with a comparator that compares the keys’ types first, then the keys.

5. The shell and the clock

Run the next cell. It builds a command from a “file name” that came from outside the program. The output of echo INJECTED shows that the shell ran a second command.

Exercise L10.5 (LO-10.2, ★★, about 20 minutes)

Write two functions:

  • shell_quote(s) returns s in single quotes for a Linux or macOS shell, with each single quote inside it written as '\'', so that the shell reads the result as one plain word.

  • days_between(from, to) takes two dates written YYYY-MM-DD and returns the number of days from from to to, as an integer, negative if to comes first. For a string that isn’t a date of that form, it returns nil and the message "not a date: " followed by the string. Make it right across changes to and from daylight saving time.

Summary

  • A <close> handle is closed on every path out of its scope, errors included, so helpers like with_file need no close of their own.

  • CSV needs a parser that tracks quotes; splitting on commas breaks quoted fields, and a reader of outside data reports bad lines with nil and a message.

  • %q and sorted keys make a serializer whose output reads back exactly and always looks the same; reading it back with load in text mode and an empty environment keeps it away from every library, but it is still code.

  • Outside input reaches the shell only quoted, and date arithmetic stays exact with noon times and whole days.

Next, do the Module 10 practice.