Modulo Operator (%)
The modulo operator % returns the remainder of a division operation. It's useful for game calculations, circular indexing, and determining even/odd numbers.
Syntax
dividend % divisorExamples
Basic modulo operations:
let a = 10 % 3; // a = 1 (10 divided by 3 is 3 remainder 1) let b = 15 % 5; // b = 0 (15 divided by 5 is 3 remainder 0) let c = 7 % 4; // c = 3 (7 divided by 4 is 1 remainder 3) print(a, b, c); // Output: 1 0 3
Game Use Cases
Checking if a number is even or odd:
let score = 42;
if (score % 2 == 0) {
print("Even score!");
} else {
print("Odd score!");
}Circular array indexing (wrap around):
let colors = ["red", "green", "blue"]; let playerIndex = 5; let colorIndex = playerIndex % len(colors); print(colors[colorIndex]); // Output: blue (index 2)
Limiting a value to a range:
// Keep angle within 0-360 degrees let angle = 450; let normalized = angle % 360; print(normalized); // Output: 90
Float Support
The modulo operator works with both integers and floats. If either operand is a float, the result is a float:
let x = 10.5 % 3; // x = 1.5 (float result) let y = 10 % 3.2; // y = 0.4 (float result)
Edge Cases
- Division by zero throws a runtime error
- Both operands must be numeric (int or float)
- Negative numbers are handled correctly
See Also
- Operators — All available operators
- ++ and -- — Increment and decrement operators
- Math module — Additional math functions