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-13.1, LO-13.2, LO-13.3, LO-13.4
Prerequisites: the Module 13 reading, a C compiler (gcc or clang), and Lua 5.4 installed as setting up describes; the lab needs Linux or macOS
Time: about 2 hours

You will predict how a sequence of C API calls changes the stack, write a C module with two checked functions, finish a C program that runs a Lua script and survives its errors, and write a userdata type whose memory the garbage collector frees. Each exercise writes a C file into the lab’s scratch folder, and Python cells compile it and run it, as you would in a terminal.

The %%lua cells of the earlier labs can’t run this lab’s code. Their Lua lives inside Python, and a C module built here can’t find the functions it calls in it: loading one fails with undefined symbol: lua_settop. So the checks run the standalone lua from the notebook environment, which exports those functions. As in the earlier labs, each check cell prints passed or fails with a message.

Setup

This cell finds the compiler and Lua’s headers and library, and defines four helpers: build_module and build_program compile a C file from scratch, run runs a program there, and lua runs Lua code there with the standalone interpreter. If anything shows NOT FOUND, install it as setting up describes, then run the cell again.

1. The stack

stack.c runs the C API operations you give it on the command line, one per argument, and prints the stack after each one, bottom first. It knows pushinteger N, pushstring WORD, pushnil, pushboolean true or false, pushvalue I, remove I, insert I, replace I, settop N, and pop N. Run the next two cells to write and compile it.

That is the sequence from the reading. Try your own in the next cell: change MINE and run it again. Keep every index within the stack: the C API doesn’t check, so an index past the top is a bug whose result is undefined, not an error message.

Exercise L13.1 (LO-13.1, ★, about 20 minutes)

Predict the stack after each step of OPS, without running them. Write each as stack.c prints it, bottom first, separated by spaces: integers as digits, strings in single quotes, and nil, true, and false as words. The first two are done. Then run the check, which names the steps you got wrong; work out why before you run show_stack(OPS) to see them.

2. A C module

Exercise L13.2 (LO-13.2, ★★, about 30 minutes)

Write the two functions of the module intmath in the next cell:

  • intmath.gcd(a, b) returns the greatest common divisor of two integers, which is never negative; gcd(7, 0) is 7 and gcd(0, 0) is 0.

  • intmath.divmod(a, b) returns two integers, a // b and a % b, equal to what Lua’s own operators give. C’s / rounds toward zero, but Lua’s // rounds down, so the two differ when a and b have different signs and b doesn’t divide a: -7 // 2 is -4 in Lua, and -7 / 2 is -3 in C. For b == 0, raise bad argument #2 to 'divmod' (division by zero).

Check both arguments with luaL_checkinteger, so that gcd(1.5, 2) raises number has no integer representation. The GCD of math.mininteger and 0, or of math.mininteger and itself, is 263, one more than the largest Lua integer: raise the error gcd out of range for it. Work with unsigned magnitudes, so the smallest integer can take part in the calculation. Handle division by -1 before using C’s signed division on the smallest integer.

Hint

For gcd, Euclid’s algorithm: replace (x, y) with (y, x % y) until y is 0, starting from the absolute values. For divmod, compute q = a / b and r = a % b in C; when r isn’t 0 and has a different sign from b, subtract 1 from q and add b to r.

3. A program that runs Lua

scorer is a C program that scores words with a Lua script: ./scorer rules.lua lua bad half loads rules.lua, calls its function score for each word, and prints each score and the total. A script is code the program doesn’t control, so scorer must report each failure and go on. Run the next cell, which writes the script the check uses.

Exercise L13.3 (LO-13.3, ★★, about 30 minutes)

Write call_score in the next cell. It calls the script’s global score with the word, in protected mode. If the call raises an error, it prints <word>: error: <message>, with the error’s message. If the result isn’t an integer, it prints <word>: error: score must return an integer. Otherwise it stores the result in *result and returns 1. Whatever happens, it leaves the stack as it found it: main prints the stack’s size at the end, which must be 0. The check expects this output for the words lua bad half tables:

lua: 3
bad: error: rules.lua:3: no score for bad
half: error: score must return an integer
tables: 6
total: 9
stack: 0

Now break the script on purpose. Change rules.lua so that it doesn’t parse, run its cell, and run the next cell: scorer should print the syntax error and exit with status 1. Then restore the script.

4. Full userdata

Exercise L13.4 (LO-13.4, ★★★, about 40 minutes)

The module bitset holds a set of bits numbered from 1 to its size, in memory that C allocates. The next cell has everything but four functions. Write them:

  • bitset_new: bitset.new(size) checks that size is an integer from 1 to INT_MAX, or raises bad argument #1 to 'new' (size out of range). It creates the userdata with lua_newuserdatauv, gives it the metatable registered as "bitset", allocates (size + WORD_BITS - 1) / WORD_BITS words of zeros with calloc, raises not enough memory if that fails, adds 1 to live, and returns the bitset.

  • bitset_set: b:set(i) sets bit i and returns b, so calls can be chained.

  • bitset_test: b:test(i) returns true if bit i is set, and false otherwise.

  • bitset_gc: __gc frees the words, sets the pointer to NULL, and subtracts 1 from live, but only if the words haven’t been freed already: a program can call __gc itself, and the collector calls it again later. Use luaL_checkudata to check its type in the finalizer. Ordinary methods use check_bitset, which also checks that the bitset is open.

Use check_bitset and check_index, which raise errors such as bad argument #1 to 'set' (index out of range). Bit i, counting from 0, is in word i / WORD_BITS, at position i % WORD_BITS; bitset_count shows how to read it, and words[w] |= 1UL << p sets it.

Hint

Set b->words = NULL and call luaL_setmetatable before calloc. If calloc fails, the error leaves a userdata whose __gc will still run, and it must find NULL there, not an uninitialized pointer.

The first check tests the methods and their errors.

The second check tests the bitsets’ lifetime. Before you run it, predict what bitset.live() returns after the loop, and again after collectgarbage. The check runs in a new lua process, so live starts at 0. A crash here, with a status such as -6 and a message about free, means that __gc freed the same memory twice.

After the loop, live is probably less than 101: the collector ran while the loop allocated, and freed some of the bitsets nothing referred to; in the course’s setup it printed 86 in one run and 72 in another, depending on the code around the loop. After collectgarbage("collect"), a full collection, only keep is left. The collector paces itself by the memory Lua allocated, though, and counts only each bitset’s 16-byte structure, not the 128 bytes of words that calloc gave it; the reading shows what that does to a program with a large heap.

Summary

  • The stack’s indices name positions from the bottom (1, 2, …) or the top (-1, -2, …), and every operation moves values among them; predicting a sequence by hand is how you debug C code that misplaces one.

  • A C module checks each argument, pushes its results, and returns their number, and its error messages name the argument, as Lua’s own functions do.

  • A host calls scripts with lua_pcall, reports what fails, and pops every result and message, so the stack ends where it started however many calls fail.

  • Full userdata gives a C structure a metatable, methods, and a type check, and __gc frees its C memory once, however many times it runs.

Next, do the Module 13 practice, and hand in the final project’s milestone.