In Lua, how can I tell if a number divides evenly into another number?
15,800
Compare the remainder of the division to zero, like this:
12 % 6 == 0
18 % 6 == 0
20 % 6 ~= 0
The modulus operator (%
) returns the remainder of division. For 12 and 6 it is 0, but for 20 and 6 it is 2.
The formula it uses is: a % b == a - math.floor(a/b)*b
Author by
Scott Phillips
Updated on June 22, 2022Comments
-
Scott Phillips almost 2 years
In Lua, how can I tell if a number divides evenly into another number? i.e with no remainder? I'm just looking for a boolean true or false.
12/6 = 2 (true) 18/6 = 3 (true) 20/6 = 3.(3) (false)
-
etandel over 12 yearsThe cool thing about % is that it works on real numbers as well
-
BMitch about 12 yearsFor comparisons to 0, the modulus operator appears to work fine. No need to make an extra function call.
-
Eric over 11 yearsWhether
-13 % 6 == 5
is incorrect a matter of opinion. This is often the behaviour you want.