Accessing Array Elements
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 63 of 92.
Each element of an array has an index, its position in the array. Indexes start at 0, so the last index is the size minus one:
var letters := ["a", "b", "c", "d"]"a"is at index 0"b"is at index 1"d"is at index 3
To read an element, write its index in square brackets after the array:
var scores := [10, 20, 30, 40, 50]
print(scores[2])30A negative index counts from the end: scores[-1] is the last element (50) and scores[-2] the one before it (40).
With a loop over range(scores.size()), the variable takes every index of the array, so you can read each element in turn:
for i in range(scores.size()):
print(scores[i])Reading an index that does not exist, like scores[5] in this 5-element array, stops the program with an error.
Challenge
EasyThe array inventory holds 6 items. The program reads a number count from the input (from 1 to 6).
- Print the first
countitems, one per line. Use a loop over the indexes. - Then print
Last:followed by the last item, read with a negative index.
For the input 3, the output is:
sword
shield
potion
Last: ropeTry it yourself
extends Node
func _ready():
var inventory := ["sword", "shield", "potion", "map", "torch", "rope"]
var count := int(OS.read_string_from_stdin())
# Print the first count items, one per line
# Then print "Last: " and the last item
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