Loops and Ranges
Lesson 9 of 48 in Coddy's GDScript for Lua Developers course.
Lua numeric for includes its terminal bound when reached by the step. GDScript range excludes its end. Translating loop bounds without adjusting this distinction causes missing or extra iterations. Lua 5.1 has break but no continue; a condition around the loop body can skip work. GDScript has both. Dense Lua sequences conventionally start at one and can be traversed with ipairs, which stops at the first nil. Use pairs for general table entries without relying on order. Do not resize a container while traversing it. The demonstration counts down, separately from the task's accumulation.
Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:
Lua file main.lua:
for n = 5, 1, -2 do print(n) end
Lua output:
5
3
1GDScript file main.gd:
extends Node
func _ready() -> void:
for n in range(5,0,-2):
print(n)
GDScript output:
5
3
1Challenge
EasyInput n is in 0..100. Return the sum of even integers from zero through n inclusive.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in exercise.gd. The supplied main.gd cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for Lua Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command CountPractice on your own: Online GDScript compiler