Help with % math operator

I don’t understand the definition that the wiki gave (https://developer.roblox.com/en-us/articles/Operators)

What does % math operator do?

2 Likes

The % operator is the modulus (or modulo) operator. It gives you the remainder of two numbers after division.

print(6 % 2) -- 0
print(20 % 3) -- 2

6 divided by 2 does not have a remainder, so 0 is returned.
20 divided by 3 has a remainder of 2, so 2 is returned.

That is one use case, for finding the remainder.

A couple more are

  • wrapping around a number. (361%360 = 1)
  • determining if a number is a multiple of another. For instance if you want to know if a number is even you can compare n%2 to 0. If n%2 == 0 evaluates to true then n is even.
21 Likes

An easy use-case is to wrap a number around to zero. For example, if you wanted an angle to go from 0 to 360 and then reset to 0, you can do this

local angle = 0
while true do
    wait(.5)
    print(angle)
    angle = (angle + 5) % 360
end
10 Likes