Skip to content

A Box That Grows From Itself

One line puts a box's own value back into it, larger. It is the counter behind every score, timer and life count.

  • Foundations

Here is a pattern used for scores, timers and life counts. LET means put the right-hand value in the named box. In this assignment, = separates the destination from the expression to work out.

Code
LET score = 0
SHOW "Score: ", score
LET score = score + 10
SHOW "Score: ", score
Output
Score: 0
Score: 10

Read it as an instruction

Read LET score = score + 10 as maths and it is nonsense. Nothing equals itself plus ten.

Read it as an instruction and it is clear: take what is in score, add ten, put the result back.

The order is what makes it work. The computer deals with the right-hand side first, using whatever the box holds right now. Only then does it put the answer back.

Stepscore beforescore afterShown
1—0—
200Score: 0
3010—
41010Score: 10

Watch step 3. score appears on both sides of the =. The computer reads the right-hand side first, adds ten to what it finds, then puts that answer back in the box.

It works in every direction

Adding to a box is only the common case. The same move takes away:

Code
LET lives = 3
LET lives = lives - 1
SHOW "Lives: ", lives
Output
Lives: 2

The starting value must exist before an update reads it. Each line finishes before the next begins, so later lines see the changed value.

With a = 2 and b = 5, do LET a = b then LET b = a swap them?

No. The first line puts 5 in a. The second reads that new value and puts 5 in b, so both end at 5. To swap them, keep the old a in a spare variable first: LET spare = a, then LET a = b, then LET b = spare.

When it’s wrong, see why

  • The value never changes. Check that you put the answer back. score + 10 on its own works the sum out and then throws it away; it needs LET score = in front of it.
  • The value resets every time. LET score = 0 is sitting somewhere it runs more than once. Set a box’s starting value once, before the part that repeats.
  • LET score = score + 10 still looks wrong to you. Good, because it is wrong as maths. Read it as “the new score is the old score plus ten”.

What you’ve learnt

  • A box can grow from its own value, which is useful for counters.
  • The computer works out the right-hand side first, then puts the answer back.
  • The same move subtracts, which is how a life count falls.
  • = means put this in the box, which is exactly why a box can grow from itself.

What’s next

You can build a value up. In Unit 3 we deal with the sums that do not come out evenly, and with the part that gets left behind.