Menu
CoddyTech

Branches and Values

Lesson 7 of 48 in Coddy's GDScript for Lua Developers course.

Lua closes branches with end and spells the middle branch elseif. GDScript uses indentation, colons and elif. Both test branches in order and choose the first matching one. Lua has no built-in conditional expression; the common condition and value or fallback idiom loses a false or nil selected value. GDScript writes the true value first in its conditional expression. Translate the decision itself, including which values count as false, rather than copying the Lua idiom. Early returns can keep invalid cases from reaching mutation. This example chooses a direction label, while the exercise classifies numbers.

Complete Lua 5.1 comparison. Run main.lua from the directory containing all shown files:

Lua file main.lua:

local n = -2
local label
if n < 0 then label = "west" else label = "east" end
print(label)

Lua output:

west

GDScript file main.gd:

extends Node

func _ready() -> void:
	var n: int = -2
	print("west" if n < 0 else "east")

GDScript output:

west
challenge icon

Challenge

Easy

Return free for amount zero, small for amounts 1..9, bulk for 10 or more, and invalid for a negative amount.

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

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

All lessons in GDScript for Lua Developers

Practice on your own: Online GDScript compiler