Double comparison

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Tort

Hey. Advise how to optimize expression.
if animation_position > 0.2 and animation_position < 0.4: - too long.
if 0.2 < animation_position < 0.4: - and it doesn’t work like that.

:bust_in_silhouette: Reply From: Bernard Cloutier
func is_between(lower_bound, upper_bound, value) -> bool:
    return lower_bound < value and upper_bound > value

func animate():
    if is_between(0.2, 0.4, animation_position):
        # do animation stuff

Also that is not what optimize means.

:bust_in_silhouette: Reply From: jgodfrey

So, you’re trying to optimize the physical length of the expression - just to make it shorter to type? Can I ask why?

Really, there’s not much you can do to the expression itself other than shortening the variable name or replacing and with &&.

Other than that, you could write a function to perform the test, which might give you a shorter calling syntax depending on your naming conventions. Something like the following (typed directly here, so untested):

if isBetween(animation_position, 0.2, 0.4):
    # do something...

func isBetween(value, low, high):
   return value > low && value < high
:bust_in_silhouette: Reply From: Tort

OK. Let it be a function.

# action in a certain position of the animation
func check_anim_pos(anim_player, value):
	if anim_player.current_animation_position > value - 0.02 and \
	anim_player.current_animation_position <= value: + 0.01)