What is math.clamp ?, Is it usefull?

Hello! :wave:
I would like to ask you guys
What is math.clamp ?
I hear this in one of topic
But is it usefull or no and how it’s working ?
Thank for any help! :heart:

2 Likes

math.clamp(x, min, max) clamps a number (x) between min and max. If it’s greater than max, it’ll return max. If it’s lower than min, it’ll return min. Otherwise, it’ll return x. You could’ve just checked the wiki, though.

4 Likes

math.clamp keeps a number within a minimum amount, and a maximum amount. This is very useful for giving a max value for IntValues.

intValue.Changed:Connect(function(value)
    intValue.Value = math.clamp(value, 0, 100) --Keeps it's value at 100 if it goes over
end)
1 Like

If you just want to keep it below a certain value, it’s better to use math.min. math.clamp is better for situations where you would want it between two numbers.

4 Likes

Thanks! :heart:
I would like ask another question
What is math.huge ?

1 Like

math.huge is how Lua represents an infinitely high number. Basically, it’s infinity. Like I said, though, you can just check the wiki page I linked earlier for an explanation.

3 Likes

I know but what is on wikie writed I don’t understand it
Anyways Thanks!

You should make different topics for different questions and not ask lots of things in one go. Also mark which post helped you as a solution so other people will find this topic useful one day.

2 Likes

“It takes 3 values. X, min and max. If X is in the range between min and max it returns X. If X is lower than min it returns min and if X is higher than max it returns max. This can be useful for tons of applications, but a good example would be constraining rotation on an axis. If you want a player to control the rotation of a brick on the Y axis but only in a 90 degree window you could clamp it’s total rotation.” A reply from a previous math.clamp explanation post. Revise the comments on this post What is math.clamp ?, Is it usefull?

5 Likes

Will this also keep it from going below 0?

1 Like

Yes. You can use it to keep numbers within a minimum and maximum range.

3 Likes

Me sitting here doing multiple if statements to achieve this same thing forgetting I used this in the past.

Thankyou, more people should look into these math operations because they can obviously be done without the operation functions Luau provides but shouldn’t be overlooked like I have in the past.

1 Like

this is what the clamp function would look like if you was to write it in lua

local function Clamp(value, minValue, maxValue)
    if value < minValue then
        return minValue
    end

    if value > maxValue then
         return maxValue
    end

    return value
end
1 Like