Lesson 4 of 10

Loops

Goal

Looping with for, while and repeat, and leaving with break

01

Explanation

The numeric loop for i = first, last, step do ... end counts from first to last, and both ends are included. The step is optional and defaults to 1. To count down you need a negative step, as in for i = 3, 1, -1. If you forget it, the loop doesn't run even once and no error appears, because 3 is already greater than 1.

When you don't know the number of iterations in advance, use while cond do ... end. It checks its condition before every iteration, so the loop might never run at all. repeat ... until cond runs its body first and then checks the condition, so it always runs at least once, and it stops when its condition becomes true, not when it fails.

break leaves the loop immediately, so you use it to stop at the first value that matches what you're looking for. Lua has no continue keyword, so if you want to skip the rest of an iteration, put the code after that point inside an if.

02

Your task

Build countdown with a loop that counts down, so it becomes "3 2 1 Go". Then use while to spend xp: as long as it covers needed, subtract needed from it, add one to level and add 100 to needed. With repeat, knock out half of enemies in each wave using integer division, and count the waves in waves until nobody is left. Finally, set firstLevel to the first value of lvl from 1 to 100 where 50 * lvl * lvl goes over ten thousand, and stop the loop there.

Checks

5 checks
  1. countdown is "3 2 1 Go"
  2. After spending XP the level is 5 with 234 left
  3. Seven waves until nobody is left
  4. The waves are written with repeat ... until
  5. firstLevel is 15, and the loop stopped there
main.lua
OutputLua 5.4 (wasmoon)

Loading Lua.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.