Modulus % operator

I am so confused because I haven’t found any topic that explains what it does and how it works. Someone please explain me.

2 Likes

basically the mod operator is used when you want to get the remainder of a division operation

for example:


print(5%2) -- returns 1 cause 2*2+1 = 5
print(5%1) --  returns 0 cause 1*5+0 = 5
1 Like

The % operator returns the remainder from division between 2 numbers.

For example, 3 % 2 would return 1, as 3 divided by 2 is 1.5, or 1 and has the remainder 1.
Other examples include:

  • 10 % 2 returning 0, as there is no remainder;
  • 5 % 6 returning 5, as 5 does not go into 6;
  • 7 % 7 returning 0, as 7 goes into 7 perfectly.
5 Likes

Modulus a % b goes hand in hand with floor division a // b (which currently isn’t natively supported by Luau, but you can use math.floor(a / b) instead)

Floor division gives you how many times something fits into something, and modulus tells you what is left out

To add on to using the math.floor() function, which was mentioned by @Prototrode as well, this is the exact formula to get the remainder of a division operation:

local formula = a - (b * (math.floor(a / b)))

which is equivalent to

local formula = a % b

still dont understand bc im bad in math


aka the remainder is the result of the % operator

print(10%2) -- returns: 2?

oh wait I has understand it. actually I learned it in school, ive just got confused lol

print(10%2) -- returns: 2?

No, it returns 0 since 10 divided by 2 equals 5, has no remainder.

That would be 0.

Another way is so think of it like this:
Say we have the following:

local Number = 7 % 3
Number = ?

Our number will be the remainder of the division of (7/3), or in other words, keep subtracting from 3 from 7 until we can’t anymore without going negative.

In this case we can subtract twice.
7 - 3 = 4
4 - 3 = 1
Thus, 7 % 3 = 1.

And in this case:

local Number = 12 % 6

12 - 6 = 6
6 - 6 = 0
Therefore, 12 % 6 = 0

4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.