How to check if number is between 10 to 20

I’m making a script to check if the players level is between 10 to 20

Script:
level.Changed:Connect(function(newlevel)
text.Text = level.Value
if level.Value >=10 or level.Value < 20 then
script.Parent.Parent.BackgroundColor3 = Color3.fromRGB(170, 0, 0) – Red

When the player is below 10, the color is changing. Its only supposed to change if the players level is between 10 or 20
Is there a better way to do this?

2 Likes

The or operator is allowing the conditional statement to pass if the Value is greater than 10 or if it’s lower than 20. This means that only one of those conditions need to be true (either a value above 10 OR a value below 20).

This can be solved by using the and operator which means that both conditions have to be met for the conditional statement to pass:

if level.Value >= 10 and level.Value < 20 then
    -- If the Value is simultaneously greater than 10 and less than 20, this condition will be met
end
2 Likes

I guess another option besides @StrongBigeMan9’s solution would be to use math.clamp

if math.clamp(Level.Value, 10, 20) == Level.Value then

end
3 Likes

Both the solutions above me work. To organize code and use NumberRange, you can use the following:

function isInRange(range, num)
   return num > range.Min and num < range.Max -- returns true if number is in range, else false
end

local numberRange = NumberRange.new(10, 20)

if isInRange(numberRange, 15) then
    -- number is in range
else
    -- number is not in range
end

2 Likes

I would say this:

level.Changed:Connect(function(newlevel)
   text.Text = level.Value
   if level.Value >= 10 and level.Value < 20 then
      script.Parent.Parent.BackgroundColor3 = Color3.fromRGB(170, 0, 0)

and continued…
line 3 is most important here.

It didn’t look good in studio but it works in Roblox. Thank you everyone who helped me. I will use the scripts here in the future in case it breaks or something.

1 Like