-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating
Godot 4 Game Development Cookbook
By :
In Godot 4, we can use typed arrays so if you are only going to use an array of strings, you can set the element type to String and Godot will throw an error if you try to put anything other than a string in that array. Types are validated at runtime and not when compiling, which causes slightly faster performance.
For this recipe, create a new scene by clicking + to the right of the current Scene tab and adding Node2D. Select Save Scene As and name it TypedArray.
In this recipe, we are going to set up three arrays. The first is not a typed array, the second is a typed array, and the third infers the type of the array:
TypedArray to Node2D and delete all the default lines except line 1 and the _ready() function.1 extends Node2D 2 3 var regular_array = [4, "hello",434]
int. Try adding a string to this array:4 var typed_array: Array[int] = [16, 32, 64]
string. Try adding an integer to this array:5 var inferred_array := ["hi", "hello"]
_ready() function, we print out all the arrays to the console:7 func ready(): 8 print(regular_array) 9 print(typed_array) 10 print(inferred_array)
Figure 2.8 – GDScript for steps 2 to 5
We added a script to Node2D and named it TypedArray. Then we deleted all of the lines in the script except line 1 and the _ready() function. We created a regular array with two integers and one string value. We can put anything in this array.
We created a typed array of int and tried to enter a string in the array to see the resulting error. In step 4, we created an inferred array of String and tried to enter an integer into the array to see the resulting error.
We printed out all of the arrays to the console. We ran the current scene. We saw [4, "hello", 434], [16, 32, 64], and ["hi", "hello"] printed on the console.