Thursday, 28 August 2014

For loop for efficiency

Most coding languages (or at least the good ones) have some sort of for loop. This is where you can iterate a task a set number of times given specific conditions, and it helps keep the code shorter.

Say, for example, I wanted to have loads of buttons all do the exact same thing when your mouse goes over them. I wouldn't create a load of individual functions for each button, because that would be very inefficient and take up a lot of space in the script! Instead I use a for loop. I iterate through a table (list/array) of the buttons, and connect a localised function to the MouseEnter event of the button that is being referenced on that iteration.

Using this method very mundane or even complex tasks can be solved with ruthless efficiency. Not only that, but if you decide you want to change something you only have to do it the once. I don't want to have to repeat the same code over and over again now, do I?

Additionally, these for loops can be built upon. You can have for loops within for loops and references within references. It may look confusing to someone not familiar with the language, but a quick overview on how it works should clear up any confusion.



A fairly intricate example of efficient  coding for GUI buttons with for loops.

No comments:

Post a Comment