How would I use math.clamp?

Hi, as you’ve seen by the title I need help with the function Math.Clamp. I’ve read various posts and the api reference for the math.clamp, but I still don’t understand how to use it. If anyone could show me how to use it or explain how to use it, in a real situation in roblox studio then, it would greatly be appreciated!

3 Likes

Math.clamp is for “restricting” a value between 2 numbers
so…

math.clamp(5,1,3) -- 3 because 5 is bigger than 2
math.clamp(2,1,3) -- 2 because 2 is less than 3 but greater than 1 
math.clamp(-10,1,3) -- 1 because -10 is less than 1

Use cases would include if you want the player to be restricted to a certain space you can use math.clamp with the position to restrict the player movement.

1 Like

when you want to limit a value between two numbers

1 Like

alright

math.clamp(-10,1,10)

what would the middle number 1 be used for?

1 Like

first value is the number you want to “clamp”, second value is min, third is max

1 Like

math.clamp() restricts a certain number x between a min number and a max number.

local minNumber = 0
local maxNumber = 10
local x = 11
local n = math.clamp(x, minNumber, maxNumber)
print(n) -- will print 10 because x > 10
2 Likes

math.clamp could be the equivalent of this function:

local function clamp(x, min, max)
    if x > max then return max;
    elseif x < min then return min;
    else return x; end
end

-- or alternatively
local function clamp(x, a, b)
    return x > b and b or x < a and a or x;
end
2 Likes

Alright, let me try testing so I can understand better

1 Like

Alright, thanks very much I understand it now!

3 Likes

The function takes x, min and max arguments and it returns the clamped value.

math.clamp(x, min, max)

Let’s say we have -10 for x, 0 for min and 10 for max.

local output = math.clamp(-10, 0, 10)

if the input is -10 then output will be 0 because -10 is less than the minimum number 0.
if the input is 20 then output will be 10 because 20 is greater than the maximum number 10.
If the input number is lower than or equal to the maximum number and greater than or equal to the minimum number, the input number won’t change.


It can be used for scripting health bar, because we don’t want health bar to display values below 0 and greater than initial health value.

healthDisplay.Text = math.clamp(health, 0, 100)
5 Likes