I've made a terrain system to generate blocks of terrain. To do this, it cuts certain vectors in half. But since it's a module script, if someone else put in an odd number, it would have a decimal number, which crashes the terrain system. So how do I detect an odd number so I can fix it?
How do I detect if a number is odd or even?
2 answers
We can use the modulus "operator" % to determine the remainder after division of a number.
If x is even, then x % 2 is 0 since 2 goes evenly into an even number.
5 / 2 is 2 with a remainder of 1. 5 % 2 is that remainder (1)
Examples:
1 % 3 is 1
2 % 3 is 2
3 % 3 is 0
4 % 3 is 1
5 % 3 is 2
6 % 3 is 0
7 % 3 is 1
8 % 3 is 2
9 % 3 is 0
10 % 3 is 1
It even works with fractions:
1 % 1.5 is 1
1.5 % 1.5 is 0
2 % 1.5 is 0.5
2.5 % 1.5 is 1
3 % 1.5 is 0
3.5 % 1.5 is 0.5
4 % 1.5 is 1
A warning about the sign (positive / negative) of the result:
The sign of a % b matches the sign of b (in Lua). So:
5 % (-2)is-1(-5) % (-2)is-1(-5) % 2is1
Simply use a modulo (%). It's used to find the remainder when dividing by something. When dividing by 2, if the remainder is 0, the number is even. Otherwise, it's odd.
if (number%2) == 0 then
--number is even
else
--number is odd
end
2 comments
BlueTaslem keeps beating me to questions.
:)
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
Thanks a ton!