7.2 Using objects
Very often, you need to iterate over all elements in a container. For example when
you draw them all on the screen. It would be very annoying if you had to remember
somehow exactly how many elements a container contains. Fortunately, you do not
have to. Containers provide a method elms() which returns the current number of
elements. And to access individual elements you can use square brackets, just like
with primitive C arrays.
for(int i = 0; i < circles.elms(); i++)
{
circles[i].draw(RED);
}
5
Because you will need an iteration like this very, very often, Esenthel provides a
‘shortcut’. A macro REPA exists to replace the whole for-loop declaration with one
instruction:
REPA(circles)
{
circles[i].draw(RED);
}
5
Remember this as ‘repeat all’. (Or don’t remember it at all. Plain for-loops will
always work just as well.) And you can do more with this than just draw every
element on the screen. Take a look at the next example and try to figure out what it
does.
REPA(circles)
{
circles[i].pos.y += Time.d();
if(circles[i].pos.y > D.h()) {
5 circles[i].pos.y -= (2*D.h() + RandomF(1));
}
}
Exercise
- Test the code above in an application. What function would you place this
code in?
- Add a function to add an extra circle every time you hit the space bar.
- Instead of a fixed radius, use a random value between 0.01 and 0.1.
- Draw only the perimeter of the circle, in white, on a blue background.
- If there are any people nearby, shout out loud what this looks like.