Created
August 27, 2024 19:54
-
-
Save sixthgear/45becc23271501690d0bcb5a3f53e334 to your computer and use it in GitHub Desktop.
Array.map (or other untyped Array returns) cast to typed array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var things: Array[Vector2] = [ | |
Vector2(1,1), Vector2(2,2), Vector2(3,3), | |
] | |
var double := func(v: Vector2) -> Vector2: | |
return v * 2 | |
# step 1: declare a typed empty array | |
var doubled_things: Array[Vector2] = [] | |
# step 2: use the assign method to automatically match the type. This is only needed | |
# for GDScript or Godot built-ins which are typed as Array or Array[Variant] | |
doubled_things.assign(things.map(double)) | |
print("is Array: ", doubled_things is Array) | |
print("is Array[Vector2]: ", doubled_things is Array[Vector2]) | |
for t in doubled_things: | |
prints(t) | |
... | |
is Array: true | |
is Array[Vector2]: true | |
(2, 2) | |
(4, 4) | |
(6, 6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment