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