+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.

in Engine by (369 points)

2 Answers

+3 votes
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")
by (1,963 points)
selected by
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"

by (108 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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.