Menu
CoddyTech

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 icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for GDScript Developers

Practice on your own: Online Lua compiler