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 2: Control flow and functions

Objectives: LO-2.1, LO-2.2, LO-2.3, LO-2.4
Prerequisites: the Module 2 reading and Lab 1
Time: about 2 hours

You will predict how many times loops run, predict how many values calls give, write a variadic function, find the stack’s limit by experiment and then step around it with a tail call, and fix a function whose defaults don’t work. As in Lab 1, 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. The second cell prints the Lua version, which should be Lua 5.4.

1. How many times does a loop run?

Each row below is the header of a numeric for, written as the part after for i =. Predict how many passes each loop makes, and replace its "?" with the number. Make all ten predictions before you run anything. The rules you need are the four in the reading’s section on the numeric for.

Exercise L2.1 (LO-2.1, ★★, about 15 minutes)

Run the check. It runs each loop, prints the values the control variable took, and compares the count with your prediction. For each mismatch, work out which rule you missed, correct the prediction, and run both cells again.

Look at row 6. Its last i prints as 0.2, but the loop stopped before a fourth pass because the next value would have been 0.30000000000000004, just over the bound. Change the bound in the next cell to 0.30000000000000004 and run it: the fourth pass appears.

2. How many values does a call give?

With the two functions in the next cell, predict the value of each expression in the cell after it: select("#", ...) counts its arguments, and # counts a table’s items. Replace each "?", then run the check.

Exercise L2.2 (LO-2.2, ★★, about 15 minutes)

Run the check, and correct each mismatch by applying the adjustment rule: a call gives all its results only when it is the last item in a list.

Exercise L2.3 (LO-2.2, ★★, about 20 minutes)

Write a global function stats(...) that takes any number of numbers and returns four values: how many there are, the smallest, the largest, and their mean. Called with no arguments, it returns the single value 0. Use select("#", ...) to count, so that the function would notice a nil among its arguments instead of stopping early.

Hint

Start smallest and largest at the first argument, (select(1, ...)), then loop from 2. The mean of integers should be a float, which / gives you.

3. The stack’s limit, and the way around it

depth(n) recurses n levels deep without a tail call. The next cell finds the largest n for which it succeeds, by binary search with pcall, which calls a function and returns false instead of stopping when it raises an error (module 6 covers it). It takes about a second. Predict the order of magnitude before you run it: a thousand, a million, or more?

Now change depth to use more stack per call: add the line local a, b, c, d, e, f = n, n, n, n, n, n before its if, and run the cell again. Each frame is bigger, so the same million slots hold fewer frames. Then remove the line again.

Exercise L2.4 (LO-2.3, ★★, about 20 minutes)

sum_to(n) adds the integers from 1 to n, but it recurses without a tail call, so sum_to(1000000) overflows the stack. Rewrite it as a proper tail call with an accumulator parameter, so that sum_to(n) still works when called with one argument. Keep it recursive: the check calls it a million levels deep.

Hint

Give it a second parameter, acc, that defaults to 0, and make the recursive call the whole of a return statement.

4. Options with defaults

make_label builds a label from a table of options: text (default ""), upper, which capitalizes the text (default false), and border, which wraps it in brackets (default true). Run the cell, and compare the third line with what its call asked for.

Exercise L2.5 (LO-2.4, ★★, about 15 minutes)

Fix make_label so that every option’s default works, including border = false. Change only the defaults that are wrong. Then, in the Markdown cell after the check, say in one sentence why opts.upper or false was harmless while opts.border or true was not.

Your sentence here: why was opts.upper or false harmless?

Summary

  • The numeric for fixes its count before the first pass; a float step can stop one pass short, or not, depending on rounding.

  • A call gives all its results only as the last item in a list, and select("#", ...) counts values, nil included.

  • Recursion without a tail call ran out of stack just under 500,000 levels for a small function, and sooner for larger frames; a proper tail call has no limit.

  • x or default is wrong for options whose valid values include false; test for nil.

Next, do the Module 2 practice, then start PA1.