Hello!
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!
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.
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)
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.
Thanks!
I would like ask another question
What is math.huge ?
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.
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.
“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?
Will this also keep it from going below 0?
Yes. You can use it to keep numbers within a minimum and maximum range.
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.
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