Wednesday, March 5, 2025

Programming: Comparing Values

I was looking up the differences between Python and Godot earlier last week, and they're actually pretty different languages.

Then, while writing my new tutorial, I ran face first into a problem that was easily solvable in Python, not so much in GDScript.

So how do you compare three values and come up with the highest variable? To be clear, if I've got: a = 1 b = 2 c = 3

I can call var whatever = max(A, B, C) and Godot will spit out 3. I don't want it to spit out 3. I want it to tell me C is the highest.

My friend was like oh just use a dictionary and I straight out died and was dead, I hate dictionaries. I don't know another way to solve them.

So apparently this will work in Python:

dictionary = {
"a" : 1
"b" : 2
"c" : 3
}

highest_value = max(dictionary, key = dictionary.get)
print(highest_value)

Hey, in Python, you don't need the var keyword!

GDScript will not do that, it doesn't like having functions in max(). Or at least 4.3 doesn't, maybe by the time you read this the fancy new version of Godot will be fine with it.

A lot of solutions I was finding involve iterating over a loop, which, like, cool, we love loops, but I got it in less lines of code, and we all know shorter is better. Here's the GDScript solution:

dictionary = {
"a" : 1
"b" : 2
"c" : 3
}

#talk to the values part of the dictionary, get the highest value
var highest_value = dictionary.values().max()
#now go back in and get the key
var this_is_the_key = dictionary.find_key(highest_value)
#prove i'm right ~
print(this_is_the_key)

It should spit out C. This is great for comparing scores and finding the winner, which is what I used it for!

No comments:

Post a Comment