Embracing Strong Typing in Godot 4

 Strong typing makes your GDScript faster, safer, and more powerful.

Variables, as you know, come in different types. Some basic types include...

TypeValuesExample
int Whole numbers (1,42,-7) var score: int = 0
float Decimal numbers (1.0, -2.75) var speed: float = 3.5
bool true or false var is_alive: bool = true
String Text var name: String = "Player"
Vector2 2D position (x, y) var start_position: Vector2 = Vector2(100, 200)
Vector3 3D position (x, y, z) var start_position: Vector3 = Vector3(1, 2, 3)
Color RGBA color var color: Color = Color(1, 0, 0)
Rect2 2D rectangle (position + size) var rect: Rect2 = Rect2(Vector2(0,0), Vector2(10,10))

In programming, typing refers to how a language keeps track of what kind of data a variable holds -like numbers, text, or Boolean values- and how strictly it enforces those rules.

There are two approaches to variables in GDScript.

Dynamic Typing

var score = 10 # Type is inferred at runtime (int)
score = "Ten" # Allowed, but dangerous - changes to type String


Strong/Static Typing (introduced in Godot 3.1)

var score: int = 10
score = "Ten" # Error! Cannot assign a value of type String as int.

Some benefits of strong typing... You catch bugs early during development, it improves code readability, and it enables better auto-completion and tool support in the Godot editor.

To practice strong typing, you explicitly declare variable types, function argument types, and function return types.

The format for variables is as follows...

var name_of_variable: type = value

Example:

var score: int = 10

For functions the format is...

func _function_name(variable: type) -> return type:

Example:

func _my_function(myVariable: int) -> int:
myVariable += 1
return myVariable

Thanks for reading, if you enjoyed this blog, be sure to share it with your friends.

Comments

Popular Posts