Look up the GDScript instructions used in Museum of Lost Lights. Each small example focuses on one job. Names such as turn_mirror refer to game instructions you define in your project. Open the related lesson checkpoints to see the whole script run.
Course contents and project downloads
First instructions and values
Comments and indentation
The hash begins a note for the reader. A colon usually opens a block. Indent the instructions that belong to that block. If power_on is true, Godot runs show_beam.
# Keep the beam inside the room.
if power_on:
show_beam()
extends
Use a Godot type as your starting point. Control already knows about sizes, input and the position of a user-interface element.
extends Control
Variables and assignment
A variable is a name for a value that may change. The assignment on the second line reads the old number, adds one and stores the result.
var moves = 0
moves = moves + 1
Type hints and inference
A type hint after a colon tells Godot which values can go into that name. The colon-equals operator infers the type from the starting value.
var moves: int = 0
var room_name := "Ocean"
Constants
Use const to name a value that stays fixed. EAST makes a movement rule easier to read than the number 1 on its own.
const EAST: int = 1
Strings and quotes
Text between quotes is a string. With two strings on either side, plus joins their text together.
var room = "Ocean"
var message = "Gallery: " + room
Format strings
%d reserves a place for a whole number. The values from the list fill the blanks from left to right. %s works well for text.
var message = "Turns: %d / %d" % [moves, goal]
Integers, floats and arithmetic
Use whole numbers for tiles and fractional values for positions or timing. Dividing two ints gives integer division. Use floats when you need the fractional part.
var tiles: int = 7 * 5
var step: float = 4.0 / 5.0
Remainders and wraparound
The remainder after dividing by four is always 0 to 3 for non-negative input. From 3, adding 1 gives 4 and the remainder is 0.
direction = (direction + 1) % 4
Booleans
A Boolean has one of two values, true and false. Store answers such as whether a player has solved the room.
var lamp_is_on: bool = false
null and Variant
Variant can hold values of different types. Null means the variable currently has no object or value. Check a value loaded from a file before using it.
var answer: Variant = null
Converting and checking types
Conversion changes how a value is represented. Use is to test the type before using methods that belong to that type.
var shown = str(moves)
if raw is Dictionary:
print(raw.size())Decisions and loops
Comparisons
Compare with two equals signs. Other comparisons include != for different, > and < for greater and smaller, and >= or <= for inclusive limits.
if lit_count == needed:
open_gallery()
and, or and not
and needs both conditions. or needs at least one. not reverses the result. Godot can stop checking as soon as the outcome is known.
if pressed and not paused:
turn_mirror()
if, elif and else
Check one branch at a time. The first branch whose test succeeds runs. The fallback after else runs if no test succeeded.
if won:
show_win()
elif moved:
show_hint()
else:
show_start()
Conditional expression
An inline conditional chooses a value. The test sits between the result for true and the result for false.
var face = "slash" if rotation == 0 else "backslash"
match
Compare one value to patterns. The underscore branch matches any value that reached it.
match direction:
0:
return "North"
_:
return "Other"
for and range
Repeat once for each item. range starts at zero when given one number. It stops before that number, which is useful for tile indexes.
for index in range(width * height):
make_tile(index)
while and break
A while loop checks before each turn. break leaves the loop. In a beam search, each turn should take a pending item or leave the loop.
while pending.size() > 0:
if found_exit:
break
inspect(pending.pop_front())
continue and early return
continue skips the rest of this loop turn. return leaves the whole function. Both can keep a rule easier to read when a special case comes first.
for tile in tiles:
if tile == source:
continue
inspect(tile)
pass
Godot requires a body for a function. pass leaves that block empty on purpose.
func wait_for_level() -> void:
passFunctions, signals and scenes
func and parameters
A function is a set of instructions you can call by name. Parameters receive values. A type after the arrow describes the result. void means the function hands no value back.
func turn(index: int) -> void:
print(index)
Arguments and default values
An argument is the actual value supplied when a function is called. A default supplies a value when the caller leaves it out.
func enter_room(name: String = "Ocean") -> void:
print(name)
enter_room()
return
Return hands the answer back to the code that called the function. Here, seven tiles fit on each row if width is seven.
func tile_index(row: int, column: int, width: int) -> int:
return row * width + column
static func
A static function belongs to the script class. It can calculate an answer without needing an individual node's state.
static func flip(face: int) -> int:
return 1 - face
Callable and bind
A Callable is a reference to instructions Godot can run later. bind supplies an argument up front. When this button is pressed, Godot calls turn_mirror with 24.
button.pressed.connect(turn_mirror.bind(24))
Anonymous functions
An anonymous function has no separate name. Store one as a callable or connect it directly to a signal when its job is small.
button.pressed.connect(func(): print("Tapped"))
signal, emit and connect
A signal is a message that a node can send. emit sends it. connect chooses which function should listen and react.
signal gallery_lit(index: int)
gallery_lit.emit(1)
Nodes, children and the scene tree
new creates a node. add_child places it in the active tree where Godot can draw and update it.
var caption = Label.new()
add_child(caption)
Scene paths and $
The dollar sign is a shortcut for finding a node by its path. Status must be a child with that name in this scene.
$Status.text = "Exhibit awake"
_ready and @onready
Wait for Godot's scene lifecycle before reading a child. An onready variable is initialised just before the node's ready function runs.
@onready var status: Label = $Status
func _ready() -> void:
status.show()
PackedScene, preload and instantiate
A packed scene is a stored group of nodes. preload prepares the scene from a project file and instantiate creates a copy.
const TILE = preload("res://tile.tscn")
var tile = TILE.instantiate()
@export and the Inspector
An export annotation exposes a variable in the Inspector. You can then edit the width from the editor and leave the script shared.
@export var room_width: int = 7
class_name and inheritance
class_name gives the script a name other scripts can use as a type. extends brings in the abilities of another type.
class_name MirrorTile
extends Control
self and super
self refers to the current object. super calls an inherited version of a method when the parent defines it.
func _ready() -> void:
super._ready()
print(self.name)
Properties and setters
A setter runs when a property is assigned. Here it keeps the stored volume between zero and one.
var volume: float = 0.5:
set(value):
volume = clampf(value, 0.0, 1.0)Collections and puzzle maths
Arrays and indexes
An array is an ordered list. Its first position is zero. A type inside brackets says which kind of value every item should be.
var rooms: Array[String] = ["Ocean", "Fossil"]
var first = rooms[0]
Adding and removing items
Append puts an item at the end. pop_back removes and returns the last item. This is useful for undo because the newest move comes back first.
history.append(24)
var most_recent = history.pop_back()
Dictionaries, keys and defaults
A dictionary pairs keys with values. Here the key is a tile index. get gives a fallback of zero if the key is missing.
var mirrors = {24: 1}
var face = mirrors.get(24, 0)
Copying and sharing
Variables can refer to the same array or dictionary. duplicate gives a separate collection. Passing true also copies nested arrays and dictionaries.
var saved_faces = mirrors.duplicate(true)
Checking membership
in asks whether an array has that item or a dictionary has that key. The beam can skip a position and direction pair it has already visited.
if index in visited:
continue
Vector2 and Vector2i
A vector packages x and y together. Vector2i is handy for whole tiles. Vector2 is handy for positions that can include fractions.
var step = Vector2i(1, 0)
var pixel = Vector2(48.0, 90.5)
From row and column to index
Rows count from the top and columns count from the left. Multiply by the width to skip the earlier rows and add the column.
var index = row * width + column
var column_again = index % width
Enums
An enum makes related named choices. These direction values start at zero by default. Direction.EAST is clearer than writing 1 throughout the program.
enum Direction { NORTH, EAST, SOUTH, WEST }
Bit flags
A number can hold a separate yes-or-no flag in each binary place. Shift the 1 to choose a place. & tests whether the stored flags include that place.
var mask = 1 << direction
var seen = (flags & mask) != 0
Queues and searching
A queue uses the oldest item next. A breadth-first search checks positions one hop away before those further away.
pending.append(next_tile)
var current = pending.pop_front()Drawing, input and time
_draw and queue_redraw
Draw reads the current state. Ask Godot for a redraw after changing the state so the artwork follows the game rules.
func _draw() -> void:
draw_line(start, finish, Color.AQUA, 4.0)
func refresh() -> void:
queue_redraw()
_process and delta
Godot supplies the time since the previous frame in seconds. Use it to keep motion or animation consistent across different frame rates.
func _process(delta: float) -> void:
elapsed += delta
_input, _gui_input and _unhandled_input
The event contains the input details. _gui_input receives the inputs that go to a Control. _unhandled_input is useful after the interface has had its chance to act.
func _gui_input(event: InputEvent) -> void:
if event is InputEventScreenTouch and event.pressed:
print(event.position)
Touch, focus and buttons
A standard Button provides a pressed signal. Moving focus gives keyboard users a clear place to start working through the controls.
retry_button.grab_focus()
retry_button.pressed.connect(restart_room)
Rectangles and colours
A rectangle groups a position and a size. A colour can come from red, green and blue values or a colour code.
var tile_box = Rect2(12, 20, 72, 72)
var frame_colour = Color("268693")
Anchors and containers
Containers place their children using layout rules. Anchors position controls relative to a parent, which helps the UI adjust to a new screen size.
var column := VBoxContainer.new()
add_child(column)
Tween animations
The tween smoothly moves a property toward a target. This glow takes one quarter of a second. The beam's rule can finish before the glow does.
var glow := create_tween()
glow.tween_property(lamp, "modulate", Color.WHITE, 0.25)
await and timers
Wait for a signal before continuing the current function. Other things in the scene can still happen while this function waits.
await get_tree().create_timer(0.5).timeout
show_next_hint()
Application pause and resume
Godot sends a notification when the app goes into the background. A save there can help the player resume later.
func _notification(what: int) -> void:
if what == NOTIFICATION_APPLICATION_PAUSED:
save_progress()
Audio on an AudioStreamPlayer
Choose the clip with stream. Play starts it. Keep sound controls independent from game rules so a quiet game still gives the player visible feedback.
player.stream = ping
player.play()Files, debugging and independent practice
Project and user file paths
res:// points inside game resources. user:// points to the game’s writable location for the current user. Store progress in user://.
const SAVE = "user://progress.json"
Reading and writing with FileAccess
Open a file and check whether it worked. Write the data, then close the handle. Keep the title screen usable if a file is unavailable.
var file = FileAccess.open(SAVE, FileAccess.WRITE)
if file != null:
file.store_string("Ready")
file.close()
JSON parsing and validation
Parsing reads JSON into a value. Check the kind of value and the fields before letting it change the game.
var data: Variant = JSON.parse_string(saved_text)
if data is Dictionary and data.has("room"):
print(data.room)
Versioned saves
A version records the shape of saved data. An upgrade can translate an old shape into the new one while preserving progress.
var data = {"version": 2, "room": 4}
Assertions and repeatable tests
An assertion checks an expectation in debug builds. A clear message shows which rule needs attention. Use regular checks for player input in release builds.
assert(tile_index(2, 3, 7) == 17, "Tile math changed")
Printing, warnings and reading errors
Print shows a value in the Output panel. A warning tells the person testing where to look. Read the first actual error and check the named file and line.
print("Beam step ", index)
push_warning("Save file could not be read")
Clamping and boundary checks
Clamping keeps a value inside a range. For an outside-the-board move, check validity and stop the beam before using the grid index.
var safe_size = clampi(raw_size, 3, 12)
Preloading assets, permissions and credits
Preload uses a path that exists when the script is loaded. Check spelling and upper-case letters. Keep the project’s art credits and permission notes close to the files they apply to.
const GODOT_ICON = preload("res://art/icon.svg")
Resources and custom data
A resource is data made to be reused. Dictionaries are an easy first format for your rooms. For a larger project, an exported custom Resource can make data editable in the Inspector.
var layout = { "width": 7, "height": 5 }
Typed signals and source ownership
Send the information the listener needs. The tile tells the board which tile was pressed. The board decides how to update the puzzle.
signal tile_pressed(index: int)
Scope and lifetime
A local name declared inside a function stays in that function. A script-level variable can keep game state across many function calls.
func example() -> int:
var count = 4
return countRunnable language experiments
Make a new Godot project with a User Interface scene, attach a script to the Control node, and paste one example at a time. Save any extra files using the names shown, then run the scene and read Godot’s Output panel.
Run a script inside the editor with @tool
Attach this to a new empty Control scene. @tool lets Godot run the script while editing as well as while playing. The Engine check chooses which of those two situations applies. Use the Output panel to read the message when you run the scene. To see the editor message, save the script and reopen the scene so its node enters the editor’s scene tree.
@tool
extends Control
func _ready() -> void:
if Engine.is_editor_hint():
print("Museum preview in the editor")
else:
print("Museum running")
Read the expected output
Museum runningMake intentional integer division explicit
The address 17 is row 3, column 2 on a five-tile-wide board. GDScript uses whole-number division when both inputs are integers, so the row calculation drops the fractional part. The annotation explains that this is deliberate. A remainder gives the column.
extends Control
func _ready() -> void:
var tile := 17
var width := 5
@warning_ignore("integer_division")
var row := tile / width
var column := tile % width
print("Row %s, column %s" % [row, column])
Read the expected output
Row 3, column 2Build an editable exhibit Resource
Save exhibit_card.gd beside the script on the Control node. It extends Resource so the card can hold data apart from the display. @export allows these properties to appear in the Inspector when you edit a saved copy of the resource. _ready fills the two properties, then reads them to tell the player which room to visit.
extends Control
const ExhibitCard = preload("res://exhibit_card.gd")
func _ready() -> void:
var card := ExhibitCard.new()
card.gallery = "Ocean"
card.target = 2
print("%s target is tile %s" % [card.gallery, card.target])
exhibit_card.gd
extends Resource
@export var gallery := ""
@export var target := 0
Read the expected output
Ocean target is tile 2Remember earlier values with a lambda
A func expression makes a Callable you can keep or return. This Callable captures counter from the call to make_counter. It changes a value in the captured Array, so the next call can keep counting. Make a second Callable to see that it has its own separate counter.
extends Control
func make_counter() -> Callable:
var counter: Array[int] = [0]
return func() -> int:
counter[0] += 1
return counter[0]
func _ready() -> void:
var first := make_counter()
var second := make_counter()
print(first.call(), " ", first.call(), " ", second.call())
Read the expected output
1 2 1Give a Callable a saved argument with bind
A Callable can be passed around before anyone calls it. bind stores an extra argument at the end of the argument list. The first argument below arrives at call time, while the second was stored when we made ocean_bell.
extends Control
func announce(message: String, gallery: String) -> void:
print("%s: %s" % [gallery, message])
func _ready() -> void:
var ocean_bell := announce.bind("Ocean")
ocean_bell.call("Exhibit awake")
Read the expected output
Ocean: Exhibit awakeProtect a dial with a setter and a getter
The set block runs when a new value is assigned to power. clampi limits a whole number to a range, here 0 through 3. get runs when the property is read. Inside its own setter or getter, power refers to the stored value instead of starting the same block again.
extends Control
var power := 1:
set(value):
power = clampi(value, 0, 3)
get:
return power
func _ready() -> void:
power = 8
print("Lamp power: ", power)
power = -2
print("Lamp power: ", power)
Read the expected output
Lamp power: 3
Lamp power: 0Wait for a signal with await
A signal tells Godot that an event happened. await pauses the current function until the signal is emitted. call_deferred arranges for wake_exhibit to run after the current work, so the waiting code has time to start listening. Read the Output panel to see the order.
extends Control
signal exhibit_awake(name: String)
func wait_for_exhibit() -> void:
print("Waiting for light")
var name_from_signal: String = await exhibit_awake
print("%s is awake" % name_from_signal)
func wake_exhibit() -> void:
exhibit_awake.emit("Jellyfish")
func _ready() -> void:
wait_for_exhibit()
wake_exhibit.call_deferred()
Read the expected output
Waiting for light
Jellyfish is awakeFind the lamps through a node group
A group is a name shared by several nodes. In this example Godot finds the room’s lamps by the group name. The observer is a Label outside that group, so the loop leaves it alone. Use groups when a rule needs a collection of scene nodes by role.
extends Control
func add_lamp(lamp_name: String) -> void:
var lamp := Label.new()
lamp.text = lamp_name
add_child(lamp)
lamp.add_to_group("gallery_lamps")
func _ready() -> void:
add_lamp("Ocean")
add_lamp("Space")
add_child(Label.new())
var lamps := get_tree().get_nodes_in_group("gallery_lamps")
print("Lamps: ", lamps.size())
for node: Node in lamps:
var label := node as Label
if label != null:
print(label.text)
Read the expected output
Lamps: 2
Ocean
SpaceLet an inherited action call its parent with super
The smaller inner class Lantern extends the Exhibit class. Both define wake. When Lantern calls super.wake(), it uses the parent version first, then adds its own ending. This works when several game objects share a general rule but have different finishing actions.
extends Control
class Exhibit:
func wake() -> String:
return "Exhibit awake"
class Lantern extends Exhibit:
func wake() -> String:
return super.wake() + " and glowing"
func _ready() -> void:
var lamp := Lantern.new()
print(lamp.wake())
Read the expected output
Exhibit awake and glowingUnpack a choice with match
match tests patterns from top to bottom. The Dictionary pattern here checks the piece key and uses var slant to bind the actual slant to a new name. The two dots allow other keys on the Dictionary. _ catches any remaining value.
extends Control
func describe(tile: Dictionary) -> String:
match tile:
{"piece": "mirror", "slant": var slant, ..}:
return "Mirror with slant %s" % slant
{"piece": "lamp", ..}:
return "Lamp"
_:
return "Floor tile"
func _ready() -> void:
print(describe({"piece": "mirror", "slant": 1, "tile": 12}))
print(describe({"room": "Ocean"}))
Read the expected output
Mirror with slant 1
Floor tileUse a typed array and a filter lambda
Array[int] holds whole numbers. filter runs a function on each item and keeps items for which the function answers true. The % remainder gives the tile column. Here the function keeps addresses in column 2 and skips other columns.
extends Control
func _ready() -> void:
var tiles: Array[int] = [10, 11, 12, 17, 18]
var column_two := tiles.filter(func(tile: int) -> bool:
return tile % 5 == 2
)
print(column_two)
Read the expected output
[12, 17]Label choices with enum and combine flags
enum gives names to whole-number values. The shifts put the choices in different binary positions. | joins choices and & tests a position. This example finds the two preferences that are enabled.
extends Control
enum Option { SOUND = 1 << 0, HINTS = 1 << 1, REDUCED_MOTION = 1 << 2 }
func _ready() -> void:
var preferences := Option.SOUND | Option.REDUCED_MOTION
print("Sound: ", (preferences & Option.SOUND) != 0)
print("Hints: ", (preferences & Option.HINTS) != 0)
print("Reduced motion: ", (preferences & Option.REDUCED_MOTION) != 0)
Read the expected output
Sound: true
Hints: false
Reduced motion: trueCopy nested room data before experiments
A shallow duplicate separates the outer Dictionary. Passing true to duplicate also copies the nested arrays and dictionaries. That is useful when an experiment edits tiles inside a room without changing the saved starting layout.
extends Control
func _ready() -> void:
var original := {"mirrors": [12, 17]}
var practice := original.duplicate(true)
practice["mirrors"][0] = 7
print("Original first mirror: ", original["mirrors"][0])
print("Practice first mirror: ", practice["mirrors"][0])
Read the expected output
Original first mirror: 12
Practice first mirror: 7Convert a checked String to a number
An input box usually gives you text. is_valid_int answers whether the String can be read as an integer. Only convert after this check. A fallback lets the player correct the value while the game keeps a valid tile address.
extends Control
func address_or(value: String, fallback: int = 0) -> int:
if value.is_valid_int():
return int(value)
return fallback
func _ready() -> void:
print(address_or("17"))
print(address_or("ocean", 10))
Read the expected output
17
10Keep exploring
Use the official GDScript language reference for the full grammar and the Godot class reference for the engine’s nodes, properties and functions.