Type Declaration
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 10 of 92.
A variable created with plain var can hold any type of value, and the type can change later:
var score = 10
score = "ten" # allowed: score now holds a StringYou can also declare the type of a variable. Write a colon and the type after the name:
var hp: int = 10
var speed: float = 2.5
var player_name: String = "Ada"
var is_alive: bool = trueA typed variable can only hold values of its type. Assigning a value of another type is an error, and Godot reports it before the program runs:
hp = 25 # OK: a new int
hp = "ten" # Error: a String cannot go in an int variableOne exception: an int stored in a float variable becomes a float, so var price: float = 5 stores 5.0.
Declared types catch mistakes before the program runs, and the Godot style guide recommends them. From this lesson on, the programs in this course give every variable a type.
Challenge
BeginnerDeclare these variables with their types, under the comment:
- an
intnamedcountwith the value10 - a
floatnamedtotalwith the value150.75 - a
Stringnamedgradewith the value"A" - a
boolnamedis_activewith the valuefalse - a
Stringnameduser_namewith the value"Bob123"
Do not change the print() lines. The program prints:
Count: 10
Total: 150.75
Grade: A
Active: false
User Name: Bob123Try it yourself
extends Node
func _ready():
# Declare the typed variables below
# Don't change the lines below
print("Count: ", count)
print("Total: ", total)
print("Grade: ", grade)
print("Active: ", is_active)
print("User Name: ", user_name)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler