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.

Objectives: LO-3.1, LO-3.2, LO-3.3, LO-3.4
Prerequisites: the Module 3 reading and Lab 2
Time: about 2 hours

You will watch the length operator as holes appear in a table, predict the borders of ten tables, write a sorted report from a record, predict what aliased tables do, finish a deep copy, measure the cost of table.remove(t, 1) and build a queue that avoids it, and fix a matrix whose rows are all one table. As in the earlier labs, each exercise ends with a check cell that prints passed or fails with a message, and the checks fail until you finish their exercise.

Setup

Nothing in this lab is random. Section 4 measures time, so its numbers depend on your machine. The second cell prints the Lua version, which should be Lua 5.4.

1. The length operator and borders

A border of t is an index whose value is present and whose next index is absent, or 0 when t[1] is absent. The next cell defines borders(t), which finds every border by trying each index from 0 to the largest integer key. It is slow on purpose: it shows what # is allowed to return, not how Lua computes it.

Run the next cell, which removes items from a sequence of eight. After each step, #t is one of the borders, but once there is more than one border, nothing says which. Then add a line of your own, such as t[9] = 90; show("t[9] = 90", t), predict both columns, and run the cell again.

The reading built two tables with the same keys and values in two different ways. Here they are again, with their borders:

Exercise L3.1 (LO-3.2, ★★, about 20 minutes)

For each table, predict its borders and replace the "?" with them as a list in increasing order, such as { 3 } or { 1, 3 }. A table with exactly one border is a sequence. Make all ten predictions before you run the check, which also prints #t for each table.

Hint

Write out which of the indices 1, 2, 3, … hold a value. Keys that aren’t positive integers, such as "x" or 0, never affect the borders, and a float key with an integer value is that integer.

2. Walking a record in order

pairs visits a table’s keys in no particular order, and the order can change between runs. Run the next cell a few times after restarting the kernel (Kernel, then Restart Kernel, then rerun the setup cells) and compare the orders.

Exercise L3.2 (LO-3.1, ★★, about 20 minutes)

Write report(stock), which takes a record like inventory and returns one string: a line name: count for each item whose count isn’t 0, in alphabetical order, joined by newlines ("\n"), with no newline at the end. For inventory it returns the five lines below, less the figs. It must not change stock.

apples: 3
kiwis: 12
pears: 4
plums: 7
Hint

Collect the names with pairs, table.sort them, then build a list of lines and join it with table.concat(lines, "\n").

3. References and copies

aliasing_story runs a short program and hands back its tables, so that the check can look at them afterward. Read it, but don’t run anything yet.

Exercise L3.3 (LO-3.3, ★★, about 15 minutes)

Predict the value of each expression at the end of aliasing_story: a number, true, or false. Replace each "?", then run the check.

Exercise L3.4 (LO-3.3, ★★★, about 25 minutes)

This deep_copy is the reading’s first version. It fails on a table that contains itself, and it turns one table that appears twice into two. Give it a second parameter, seen, that maps each original table to its copy, so that both cases work. deep_copy(t) must still work when called with one argument.

Hint 1

Create seen on the first call with seen = seen or {}, and pass it to every recursive call.

Hint 2

Store the new copy in seen[value] before the loop that fills it. A table that contains itself then finds its own copy in seen when the loop reaches it.

4. What a queue costs

The next cell empties lists of 2,500 to 20,000 items with table.remove(t, 1), and prints how long each took and how many times longer than the row above. Before you run it, predict that ratio: when the list doubles, does the time double, or grow by more? The cell takes about 3 seconds.

Each doubling multiplies the time by about four, because each removal moves every remaining item: emptying n items moves about n2/2n^2/2 of them, which is O(n2)O(n^2).

Exercise L3.5 (LO-3.4, ★★, about 20 minutes)

Write a queue whose push and pop are both O(1)O(1), as four global functions:

  • queue_new() returns a new, empty queue;

  • queue_push(q, value) adds value at the back;

  • queue_pop(q) removes and returns the value at the front, or returns nil when q is empty;

  • queue_size(q) returns the number of values in q.

Any value except nil can be queued, false included. The check times 20,000 pushes and pops, and fails if they take 0.25 s or more, which a queue that moves its items on every pop does.

Hint

Keep two indices, first and last, in the queue’s table, next to a table of items. When you pop, set the popped slot to nil so the queue doesn’t keep a reference to it.

5. A matrix

new_matrix(rows, cols, fill) should build a rows-by-cols matrix filled with fill. Run the cell, and compare the two numbers it prints with what the code meant to do.

Exercise L3.6 (LO-3.3, LO-3.4, ★★, about 20 minutes)

Fix new_matrix, so that each row is a table of its own. Then write transpose(m), which returns a new matrix t with t[j][i] == m[i][j]: a 2-by-3 matrix becomes a 3-by-2 one. Assume m has at least one row and that all its rows have the same length. transpose must not change m, and must not share any row with it.

Summary

  • #t always returns a border of t. A sequence has one border, its length; a table with holes has several, and which one # returns depends on how the table was built.

  • pairs has no order to rely on; sort the keys to get one.

  • Assigning or passing a table shares it, and == compares identity. A deep copy needs a seen table to copy shared and self-containing tables correctly.

  • table.remove(t, 1) moves every item, so emptying a list that way is O(n2)O(n^2); a queue with two indices is O(1)O(1) for each push and pop.

  • Every row of a matrix must be a table of its own.

Next, do the Module 3 practice.