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 intAdding 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
EasyThe program reads a count from the input, then that many scores, one per line.
- Declare
scoresas an empty typed array of integers - Read each score, convert it with
int()and append it toscores - Print
scores, thenBest:followed by the highest score
For the input below, the output is:
3
70
95
88[70, 95, 88]
Best: 95Try 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler