Learn Lua · Basics · Lesson 3 of 4
Repeating with loops
A for loop runs the same code for each number in a range. for n = 1, 4 do … end
runs with n set to 1, 2, 3 and then 4:
local total = 0
for n = 1, 4 do
total = total + n
end
total --> 10A third number sets the step, so for n = 3, 1, -1 counts down: 3, 2, 1. The %
operator gives the remainder after dividing, so n % 2 == 0 is true for even numbers:
7 % 2 --> 1
8 % 2 --> 0.. joins text, and joins numbers as text too: "Page " .. 3 is "Page 3".
What your code receives
Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.
input = { last = 4 }Steps
- Return
total: every whole number from 1 toinput.lastadded together. - Add
evens: how many of those numbers are even. - Add
countdown: the numbers frominput.lastdown to 1 as text, separated by spaces, such as"3 2 1".
Show a hint
Use one loop for total and evens, and a second one that counts down for countdown. Add a space before every number except the first.