|
| 1 | +--- |
| 2 | +title: "Chapter 3.2" |
| 3 | +--- |
| 4 | + |
| 5 | +# Chapter 3.2: Walk and While |
| 6 | + |
| 7 | +## Loops |
| 8 | + |
| 9 | +When you need to run a block of code multiple times, you use a **loop**. |
| 10 | + |
| 11 | +Loops let your program “cycle” through code, whether that’s repeating an action _x_ number of times or continuing until a condition changes. |
| 12 | + |
| 13 | +GLang gives you two main ways to loop: `while` and `walk`. |
| 14 | + |
| 15 | +## `while` |
| 16 | + |
| 17 | +A `while` loop is basically an `if` statement that keeps running **while** a condition remains true. |
| 18 | +If that condition never becomes false, your loop will run forever (and probably melt your computer’s hardware). |
| 19 | + |
| 20 | +``` |
| 21 | +while true { |
| 22 | + bark("This loop runs forever!!!"); |
| 23 | +} |
| 24 | +```` |
| 25 | +
|
| 26 | +Of course, infinite loops aren’t always bad, sometimes you want your program to keep running until something happens. For example, you might want to increment a value until it hits a goal. |
| 27 | +
|
| 28 | +``` |
| 29 | +obj x = 0; |
| 30 | + |
| 31 | +while x != 100 { # stops when x == 100 |
| 32 | + x = x + 1; |
| 33 | +} |
| 34 | +``` |
| 35 | +
|
| 36 | +A classic example is a game loop that runs while the game is active: |
| 37 | +
|
| 38 | +``` |
| 39 | +while game_is_running() { |
| 40 | + render_opponent(); |
| 41 | + render_player(); |
| 42 | +} |
| 43 | +``` |
| 44 | +
|
| 45 | +## `walk` |
| 46 | +
|
| 47 | +The `walk` loop gives you more **control**. Instead of looping until some condition changes, you define exactly how many times it should run. |
| 48 | +
|
| 49 | +``` |
| 50 | +walk i = 0 through 10 { |
| 51 | + bark(i); |
| 52 | +} |
| 53 | +``` |
| 54 | +
|
| 55 | +Here’s what happens: |
| 56 | +
|
| 57 | +- `i` starts at 0 |
| 58 | +- The loop runs while `i` is less than 10 |
| 59 | +- Each time through, `i` increases by 1 automatically |
| 60 | +
|
| 61 | +So this prints: `0, 1, 2, 3, 4, 5, 6, 7, 8, 9`. |
| 62 | +
|
| 63 | +You can also control how much `i` increases each time with the optional `step` keyword: |
| 64 | +
|
| 65 | +``` |
| 66 | +walk i = 0 through 10 step = 2 { |
| 67 | + bark(i); # outputs 0, 2, 4, 6, 8 |
| 68 | +} |
| 69 | +``` |
| 70 | +
|
| 71 | +## Your Challenge 🤔 |
| 72 | +
|
| 73 | +Use a `walk` loop to output numbers 0 - 10000 counting by 100s (0, 100, 200). |
| 74 | +
|
| 75 | +::: details Answer |
| 76 | +``` |
| 77 | +walk i = 0 through 10000 step = 100 { |
| 78 | + bark(i); |
| 79 | +} |
| 80 | +``` |
| 81 | +::: |
0 commit comments