Modulos!

What does a modulo do? Well, in terms of constraining values, it certainly saves a lot of lines of code! I'd been introduced to modulos before early in the first term on in one of the processing coding classes(last year now), but I'd never really employed them in my code, until now! Many thanks to Roy for showing me how to save myself a lot of 'if' statements by simply using the humble modulo function...

The wikipedia article describes the modulo function quite elgegantly: "In computing, the modulo operation finds the remainder after division of one number by another (sometimes called modulus)". (There is a lot more explanation than that of course, but I'm just going to talk about it in laymans terms here)

So what's cool, from a programming perspective is that the 'modulus', is returned as a whole number rather than a decimal as you'd get from simple division on a calculator. So for example, 1/100 = 0.01, so the modulus of this would be 1. The same goes for each number up to 100, wherein the modulus would then be 0 (100/100 = 0).

This is especially useful for constraining a variable to a maximum number. For my purposes, using live video with openFrameworks(where the C++ syntax for modulo is simple '%') I wanted to just draw a 'scan' line across an image. Simple stuff. I set a global variable to 0 and use the '++' operator in the update function to add one for each drawing loop. I use this value for the X co-ordinates of my line and viola, the line moves across the drawing canvas. But what if I want the line to start from the beginning again once it's reached the opposite side? Again, another simple programming solution, just use an 'if' statement, I might have something like this:

variable ++; if(variable > canvasWidth){ variable = 0;}

This will reset the variable (which is just acting as an incremental counter in this case) to zero once it goes over the width of the canvas.

Simple, yes, but the modulo makes this even simpler! Instead, I can just write this:

variable ++; variable %= canvasWidth;

If I console log the result of the variable, I will get the same output in each case, but I've saved myself a line of code by just using the modulo function instead of the 'if' statement. Lovely :).