Menu
CoddyTech

Typed Arrays

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 68 of 92.

A plain array accepts values of any type. A typed array accepts only one type, written in square brackets after Array:

var scores: Array[int] = [90, 85, 77]
var players: Array[String] = ["Ana", "Ben"]
var bonuses: Array[int] = []

GDScript checks every value. A value of the wrong type in the brackets is reported before the program runs:

var scores: Array[int] = [90, "high"]  # Error: "high" is not an int

Adding a value of the wrong type while the program runs is an error too, and the value is not added:

var scores: Array[int] = [90, 85]
var bonus = "ten"
scores.append(bonus)  # Error, scores stays [90, 85]

Type inference with := does not create a typed array: var scores := [90, 85] is a plain Array. Write Array[int] to get one.

Because a typed array knows its element type, var best := scores[0] infers int. With a plain array, the same line is an error, since its elements can be of any type.

Typed arrays have the same indexes and methods as plain arrays, and print(scores) shows them the same way: [90, 85].

challenge icon

Challenge

Easy

The program reads a count from the input, then that many scores, one per line.

  1. Declare scores as an empty typed array of integers
  2. Read each score, convert it with int() and append it to scores
  3. Print scores, then Best: followed by the highest score

For the input below, the output is:

3
70
95
88
[70, 95, 88]
Best: 95

Try it yourself

extends Node

func _ready():
	var count := int(OS.read_string_from_stdin())
	# 1. Declare scores, an empty typed array of int
	# 2. Read count scores and append each one
	# 3. Print scores, then "Best: " and the highest score
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler