# Use cases for math.clamp(), math.min(), and math.max()

I already know what `math.clamp()` does, but i was wondering about `math.min()` and `math.max()`, for some reason, I keep confusing it with another math function in Base Lua (unless its the same thing), but feel free to ignore this part, It’s not really what I’m asking for.

I was just wondering about the use cases for them.

Anything helps.

2 Likes

math.min returns the lowest value in a list, and math.max will return the highest value

e.g.
math.min(5, 7, 1, 3, 9) will return 1, as it is the lowest

math.max(5, 7, 1, 3, 9) will return 9, as is it the heightest

5 Likes

The use case is when you want to modify and control a measured number that you obtain anywhere.

Such as player input for buying items they can input -50 which is not desired.

Therefore you use math.min to set it to zero an avoid negative numbers.

Another case is making gun damage drop off from a damage function based on distance. Damage variable is the one being modified. Math.clamp is used to add a maximum and mininum value.

The third case is physics related such as speed control when you want to limit speed or velocity magnitude a measured variable. There you use math.max to limit the speed.

There are definitely more cases but these are the ones I can think of right now.

Tl;DR control a number by adding a maximum (math.max) or minimum limit (math.min) or both (math.clamp)

1 Like

`math.min()` and `math.max()` are the same in luau as in lua

Min is to find the smallest value/apply a minimum limit
Max is to find the largest value/apply a maximum limit
Like others have said.

Also I’m pretty sure internally `math.clamp(val, min, max)` is just `math.min(max, math.max(val, min))`

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