while and repeat
Lesson 13 of 48 in Coddy's Lua for GDScript Developers course.
A GDScript while loop checks its condition before entering the body. Lua's while condition do ... end follows the same rule, which is useful when zero work must produce zero iterations. Lua also provides repeat ... until condition. That loop runs its body at least once and finishes when the condition becomes true. GDScript has no direct repeat-until statement; a while true loop with a final conditional break can express it. When repeatedly halving a nonnegative count, use math.floor(count / 2) in Lua. Ordinary division can leave fractions instead of reaching the intended integer stopping state.
GDScript 4
extends SceneTree
func _init():
var count = 0
var steps = 0
while count > 0:
count = count / 2
steps += 1
print(steps)
quit()Lua 5.1
local count, steps = 0, 0
repeat
count = math.floor(count / 2)
steps = steps + 1
until count == 0
print(steps)Porting trap
until states when to stop, not when to continue. A zero-input calculation that requires zero steps should use a prechecked while loop.
Challenge
EasyInput n is a nonnegative integer. Repeatedly halve it with floor division until zero. Return the number of halvings. Zero needs zero steps.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for GDScript Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte IndexesRecap: Format a Receipt4Functions and Closures
Functions and ReturnsDefaults and Missing ValuesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
null and Missing FieldsTruth and Default ValuesBranches and BoundsEquality and IdentityRecap: Admission Rules3Iteration and Flow
Ranges to Numeric forwhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsPatterns Instead of RegexScripts to requireError Results and pcallRecap: Validate a BatchPractice on your own: Online Lua compiler