Menu
CoddyTech

Accessing 2D Array Elements

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 13 of 78.

To reach one cell of a 2D array, use two indices: the first picks the row, the second picks the column inside that row. Both start at 0.

var level := [
	[1, 1, 1, 1],
	[1, 0, 2, 1],
	[1, 1, 1, 1]
]
print(level[1][2]) # 2 (row 1, column 2)
print(level[0][0]) # 1

level[1] returns the row [1, 0, 2, 1], and [2] then picks index 2 of that row. Negative indices count from the end, as in any array: level[-1][-1] is the bottom-right cell.

Assign to a cell to change it. When the player picks up the coin, its tile becomes floor:

level[1][2] = 0
print(level[1]) # [1, 0, 0, 1]

An index outside the grid is an error that stops the program: level[3][0] fails because the rows go from 0 to 2. When the indices come from input or from a calculation, check them against the size of the grid first:

var row := 2
var col := 5
if row >= 0 and row < level.size() and col >= 0 and col < level[row].size():
	print(level[row][col])
else:
	print("Outside the map")

This prints Outside the map, because column 5 does not exist. and stops at the first condition that is false, so level[row] is only read when the row exists.

challenge icon

Challenge

Easy

Write a function named get_tile with three parameters:

  1. grid: a 2D array of integers (declare it as grid: Array)
  2. row: a row index
  3. col: a column index

It returns the value at that row and column. If row or col is outside the grid (less than 0, or not less than the number of rows or columns), it returns -1 instead. Negative indices count as outside.

For example, get_tile([[1, 2, 3], [4, 5, 6]], 1, 2) returns 6, and get_tile([[1, 2], [3, 4]], 2, 1) returns -1.

The tests call get_tile() themselves and check the value it returns. Do not call it and do not print anything.

Try it yourself

func get_tile(grid: Array, row: int, col: int):
	# Write code here
	pass
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler