Most Efficient Way to Return the Highest Value?

What’s the most efficient way to return the highest of two values? I’m looking for something like


var = high and low

print(var) -- returns high

I could obviously just use normal if and else statements but a different way would be so much cleaner for something that should only take one line in the first place.

local variable1 = 2
local variable2 = 5

local highest = (variable1 > variable2 and variable1) or variable2
2 Likes

Thanks, I thought about using ternary operators

How could I add a ‘not equal clause’? I’m comparing the scores of each team at the end of a game, so I don’t want one team to win even if they’re equal.

var = math.max(high, low, medium, ...) -- should be high
2 Likes
local variable1 = 2
local variable2 = 5

local isEqual = variable1 == variable2
local highest = not isEqual and ((variable1 > variable2 and variable1) or variable2)

Now it’s getting a bit overboard though, why are you against using if statements, etc…?

Thanks lots, but another user found another method. Nothing wrong with if statements, but I feel like this type of thing should only take one line. Neither are perfect but I’ll try both and see what I can work with. Several just feels awkward, haha.

If you’re only computing two numbers, then calling the math library rather then using an arbitrary equation (such as greater then, etc…) is going to be more performant hindering.

Good code does not always mean stuck on one line, keep that in mind. Both the example I sent as well as the other user quite frankly are poor habits.

Nonetheless, glad you found a solution.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.