Arrays in GDScript
Our first example demonstrates the use of arrays in GDScript. In GDScript, an array is a collection of elements that can be of any type.
extends Node
func _ready():
# Here we create an array 'a' that will hold exactly 5 integers.
# By default, an array is initialized with null values.
var a = [null, null, null, null, null]
print("emp:", a)
# We can set a value at an index using the array[index] = value syntax,
# and get a value with array[index].
a[4] = 100
print("set:", a)
print("get:", a[4])
# The built-in len() function returns the length of an array.
print("len:", len(a))
# Use this syntax to declare and initialize an array in one line.
var b = [1, 2, 3, 4, 5]
print("dcl:", b)
# In GDScript, arrays are dynamic, so we don't need to specify the size.
# We can simply add elements to the array.
b = [1, 2, 3, 4, 5]
print("dcl:", b)
# GDScript doesn't have a direct equivalent to Go's index-based initialization,
# but we can achieve a similar result using a combination of array operations.
b = [100]
b.resize(4)
b.append(500)
print("idx:", b)
# Array types in GDScript can be multi-dimensional.
var twoD = []
for i in range(2):
var row = []
for j in range(3):
row.append(i + j)
twoD.append(row)
print("2d: ", twoD)
# You can create and initialize multi-dimensional arrays at once too.
twoD = [
[1, 2, 3],
[1, 2, 3]
]
print("2d: ", twoD)
# To run this script, attach it to a Node in your Godot scene and run the scene.
# The output will be visible in the Godot output panel.
Note that arrays in GDScript are printed in the form [v1, v2, v3, ...]
when using the print()
function.
When you run this script in Godot, you should see output similar to the following in the output panel:
emp: [null, null, null, null, null]
set: [null, null, null, null, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, null, null, null, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [1, 2, 3]]
This example demonstrates the basic operations and concepts of arrays in GDScript. Unlike statically-typed languages, GDScript arrays are dynamically-sized and can hold elements of different types. The syntax for creating, accessing, and modifying arrays is straightforward and flexible, making them a powerful tool for organizing and manipulating data in your Godot projects.