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-7.1, LO-7.2, LO-7.3
Prerequisites: the Module 7 reading and Lab 6
Time: about 2 hours

You will predict which metamethod each operation calls and with what arguments, give a vector type its operators, give tables default values, build a read-only view that protects nested tables too, and predict which entries of weak tables survive a garbage collection. As in the earlier labs, each check cell prints passed or fails with a message, and the checks fail until you finish their exercise.

Setup

Nothing in this lab is random, and section 5’s garbage collections happen at moments the code chooses. The second cell prints the Lua version, which should be Lua 5.4.

1. Which metamethod runs?

The next cell makes tracer, a metatable whose metamethods each return a string naming themselves and the types of the arguments they got, and two tables t and u that use it. Run it, and try print(t + u) in a cell of your own.

Exercise L7.1 (LO-7.1, ★★, about 15 minutes)

Predict the value of each expression. For most, it is the string the metamethod returns, such as "__add(table, number)"; for a comparison it is a boolean. Make all twelve predictions before you run the check.

2. A vector type

Exercise L7.2 (LO-7.1, ★★, about 25 minutes)

vec(x, y) makes a two-dimensional vector whose metatable is vector_mt. Give vector_mt these metamethods:

ExpressionResult
a + b, a - bA new vector, added or subtracted component by component
2 * a, a * 2A new vector, each component multiplied by the number
a * bThe dot product, a number: a.x * b.x + a.y * b.y
-aA new vector with both components negated
a == btrue when both components are equal
tostring(a)The string "(x, y)", such as "(1, 2)"

No operation may change its operands.

Hint

2 * a calls vector_mt.__mul(2, a), with the number first. Test type(a) == "number" and type(b) == "number" to tell the three cases of * apart.

3. Default values

Exercise L7.3 (LO-7.2, ★, about 15 minutes)

Write with_default(t, default), which gives t a metatable so that every key t doesn’t have reads as default, and returns t. Reading a missing key must store nothing. Make it work when default is false.

Hint

__index can be a function of the table and the key. A table as __index won’t do here: default is a single value, not a table of keys.

4. A read-only view, all the way down

The reading’s read_only protects the top level of a table only: ro.window.title = "x" still changes the nested table, because ro.window is the real one.

Exercise L7.4 (LO-7.2, LO-7.3, ★★★, about 35 minutes)

Write deep_read_only(t), which returns a read-only view of t at every depth:

  • Reading a value that isn’t a table returns it. Reading a table value returns a read-only view of that table, and the same view every time: ro.window == ro.window.

  • Any assignment through a view, at any depth and to any key, raises the error "attempt to change a read-only table" at level 2.

  • # and pairs work on every view, and pairs gives views for table values. The view shows later changes made to the original.

Hint 1

Keep a table that maps each original table to its view, and look there before making a new view. Give it weak keys, so that the cache doesn’t keep tables alive that the program has forgotten.

Hint 2

Make __index a function that reads t[k] and passes the result through deep_read_only, which returns non-tables unchanged. __pairs returns an iterator built on next(t, k) that does the same for each value.

5. Weak tables

weak_story builds four tables, three of them weak, fills them, forces a full garbage collection with collectgarbage(), and reports what survived. Read it before the exercise, but don’t run anything yet.

Exercise L7.5 (LO-7.3, ★★, about 15 minutes)

Predict each value weak_story reports: a number of entries, or true if the entry survived and false if it was removed. Then run the check.

Last, watch a weak cache empty. The cell caches an area for each of 1,000 shapes, drops every shape but one, and counts the cache’s entries before and after a collection. The collector also runs on its own whenever the program has allocated enough memory, so the cell stops it first, with collectgarbage("stop"); otherwise it might empty the cache before the first count. Try removing that line and running the cell a few times.

Summary

  • A binary operator’s metamethod gets both operands in their original order, from whichever operand has it; == calls __eq only for two different tables.

  • Metamethods for arithmetic, ==, and tostring make a table behave like a value type, as long as every operation returns a new table.

  • A function in __index supplies defaults without storing them.

  • An empty proxy sees every read and write; a weak-keyed cache of proxies gives one view per table without keeping the tables alive.

  • Weak tables drop entries whose weak part is an unreachable object, at the next collection; strings, numbers, and the entries of ordinary tables stay.

Next, do the Module 7 practice, then take Self-test 1.