Garry's Mod Wiki

math.Clamp

  number math.Clamp( number input, number min, number max )

Description

Clamps a number between a minimum and maximum value.

Arguments

1 number input
The number to clamp.
2 number min
The minimum value, this function will never return a number less than this.
3 number max
The maximum value, this function will never return a number greater than this.

Returns

1 number
The clamped value.

Example

Demonstrates what this function does.

print( math.Clamp( 10, 0, 5 ) ) -- 10 is greater than 5 so returns 5 print( math.Clamp( 3, 0, 5 ) ) -- 3 is greater than 0 and less than 5, so returns 3 print( math.Clamp( -1, 0, 5 ) ) -- -1 is less than 0, so returns 0
Output:
5 3 0

Example

Heals player by 10%, but won't let their health go above 100.

ply:SetHealth( math.Clamp( ply:Health() + 10, 0, 100 ) )