0 votes

I want to have a variable assigned based on the value of another variable. Because the second variable can have lot of different values, instead of having a lot of if statements, if I can, I'd rather use something that checks equivalence within anywhere in an array and picks the element within that array that matches to assign to the first variable.

So "if x equals anything in array [a, b, c, d]
y = the element x is equal to"

Godot version 3.2.3
in Engine by (44 points)

1 Answer

+1 vote

while not the most performant, you can simply

for i in array:
    if x == i:
        y = x
        break

or better (this should also work afaik):

if x in array:
    y = x
by (291 points)

Let's go after the doc writers /s

Perhaps instead of having an array of variables you can just modify the array directly? If you need names you can use a dictionary as well.

Maybe a dictionary will work. I don't know how those work yet.

I've got it

func _ready():
    for i in pdic:
        if piece_type == pdic[i]:
            var keyl = pdic.keys()
            for n in pdic.keys():
                if n == i:
                    pt = n

Since "i" is already the key, you only have to do this:

for key in dictionary:
    if a == dictionary[key]:
        b = key
        break
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 Frequently asked questions and 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 [email protected] with your username.