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
0is an integer: a length that starts at zero is0um, ordefine 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.