laylight tour
0/25
4/4

Loops and values · 4 of 4

Variables and lists

Inside a block, define creates a variable. Unlike parameters, attributes and global constants, a variable can change: give it a new value with =, or add to a list with append:

define x = 0um
define xs: [size] = []
for i in 0..4 {
    xs.append(x)
    x = x + 10um
}
# xs is now [0, 10um, 20um, 30um]

A variable lives until the end of the block that defines it. Its type comes from its first value, so two cases need care:

  • an empty list needs its type written out, [size], [point] and so on, since there is nothing to infer it from;
  • a plain 0 is an integer: a length that starts at zero is 0um, or define x: size = 0.

Lists are indexed from 0 — xs[1] — and len(xs) is their length. polygon and path take lists of points, so a loop can build the outline of a shape point by point.

Exercise

Draw a square spiral as a single path. From the origin, go pitch to the right, then 2 × pitch up, 3 × pitch to the left, 4 × pitch down and so on, turning left every time, for 4 × turns segments. Collect the corners in points with append, then draw the path through them.

loading compiler…

Edit the code, watch the layout, then press Submit to check your solution against the exercise.

Compiling…