What you learn today
- select instead of jumps
- Subroutines
- Loops instead of repetition
Four tanks, four lights: full or not. The first draft has the same block with jumps for every tank, 44 lines in total. With four tanks that still works. With twelve it no longer does – and by then at the latest it pays to look at the three tools for saving lines.
select instead of jumps
An if-then-else with jumps needs a label for every branch and a jump over the other one:
bgt press FULL full1
sbn LIGHT HASH("T1") On 0
j next1
full1:
sbn LIGHT HASH("T1") On 1
next1:
The same with a comparison instruction that returns 0 or 1:
sgt full press FULL
sbn LIGHT HASH("T1") On full
Six lines become two. Where two different numbers are meant, use select – select colour full Color.Red Color.Green replaces a whole branch.
Subroutines
If a block that does more than two lines repeats, it becomes a subroutine (day 127): written once, called several times with jal. You pass the values in registers. Each call costs two to four lines instead of the whole block.
Loops instead of repetition
If the repetitions only differ by the device name, a loop is even shorter. The names sit in a table in the stack, the loop walks through them:
loop:
get name db i
lbn press TANK name Pressure Average
sgt full press FULL
sbn LIGHT name On full
add count count full
add i i 1
blt i COUNT loop
For a fifth tank one poke line is added and COUNT becomes 5. The rest stays.
| Version | lines |
|---|---|
| four blocks with jumps | 44 |
loop with sgt | 29 |
| loop for twelve tanks | 37 |
Shorter does not mean faster. The loop executes a few more instructions per tank than the written-out block – labels and the jump back cost too. More on that tomorrow with the instruction budget.
Light and the pipe analyzer at the tank carry the same name here. Because sbn also checks the device type, sbn LIGHT name … only hits the light. That way one name table is enough for both.
Diagram
Exercise
Task
The starter code does everything right, but with four identical blocks full of jumps. Rewrite it as a loop over a name table “T1”–“T4”, without conditional jumps except the loop's jump back (blt):
- light “Tn” on when tank “Tn” has more than 5000 kPa
- display “Volle” counts the full tanks
- a missing tank counts as not full
Hints
Hint 1
Before start: four poke lines with the name hashes.
Hint 2
In the loop: get name db i, lbn … name Pressure Average, sgt full press FULL.
Hint 3
sgt with NaN gives 0 – the missing tank therefore does not count by itself.
Quiz
3 questions. You pass from 60 % – the server does the grading.
Complete the day
- Passed the simulator exercise
- Passed the quiz with at least 60 %
Without an account progress is saved in this browser only.
Report a mistake in this lesson
Please sign in to report. Sign in