Learn

Chapter 03 Conditions, Time & Loops

#024 For Loop

First Index 0, Last Index 5. How many times does it run? Six.

  • 0:55 video
  • Written lesson
  • Beginner
Video lesson: For Loop, 0:55

Inclusive on both ends

For Loop takes a First Index and a Last Index, and both are inclusive: 0 to 5 runs six times. Loop Body fires once per index, and the Index pin gives the current number. Then Completed fires once.

Every iteration runs during one frame. The game waits until the loop finishes.

Example: one enemy per lane

Spawn five enemies, one per lane: First Index 0, Last Index 4. Loop Body calls Spawn Enemy, and Index picks each lane. Unsure? Print the Index: 0, 1, 2, 3, 4, then Completed.

The classic mistake

Putting a Delay inside Loop Body. The loop never waits: all iterations start immediately, and the Delay completes only once.

More details

  • Looping over an array? Last Index is Length minus one.
  • Past a million iterations, you get an infinite loop error by default.
  • Need to stop early? That’s For Loop with Break, the next episode.

In short

Inclusive on both ends, all in one frame.

Covered in this lesson

  • For Loop
  • First Index
  • Last Index
  • Loop Body
  • Index
  • Completed
  • Length

Newsletter

Development updates are coming to your inbox.

The newsletter opens soon. Until then, new lessons, tools and Beach Hunters progress appear first on our channels, linked below.