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]) # 1level[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
EasyWrite a function named get_tile with three parameters:
grid: a 2D array of integers (declare it asgrid: Array)row: a row indexcol: 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler