+1 vote

I have a variable var Peter = 0 and then I set this variable to a string or a int and then I want to do something if it is a string and I want to do something if it is an int.

asked Jul 2 in Engine by Godot_Starter (265 points)

2 Answers

+1 vote
Best answer

Use typeof()

Use this list as a reference.

if typeof(Peter) == TYPE_STRING:
    print("I'm a string")
elif typeof(Peter) == TYPE_INT:
    print("I'm an int")
answered Jul 2 by deaton64 (1,205 points)
selected Jul 2 by Godot_Starter
0 votes

Another solution is to use the is logical operator:

if Peter is String:
    print("I'm a string")
elif Peter is int:
    print("I'm a integer")
elif Peter is Spatial:
    print("I'm a spatial")
elif Peter is Resource:
    print("I'm a resource")

and so on.

A good practice is to type your variable, this will avoid type testing and will increase performance of your code:

var Peter:int = 0

The editor will complain if you write further:

Peter = "my best friend"

answered Jul 3 by frankiezafe (86 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.