Menu
CoddyTech

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])
30

A 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 icon

Challenge

Easy

The array inventory holds 6 items. The program reads a number count from the input (from 1 to 6).

  1. Print the first count items, one per line. Use a loop over the indexes.
  2. Then print Last: followed by the last item, read with a negative index.

For the input 3, the output is:

sword
shield
potion
Last: rope

Try 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
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