Script flow functions - For Next Loops

Top  Previous  Next

Introduction

 

Keep walking.

Could you repeat that ?

Make 10 circles around the stadium !

 

Above mentioned expressions are used every day, and nobody is used to say:

 

Keep making loops with your legs.

Could you loop what you just said ?

Loop around the stadium 10 times !

 

Although it sounds funny, at the same time it's true - moving one leg in front of another repeatedly is a loop, just as circulating around the stadium. Engines use loops too:

 

EngineLoop

 

Millions of people work on factory lines, having loops as their work basics:

WorkerLoop

 

And in all these cases there's no help - actions must be repeated manually, sometimes with help from automatized machines. And talking about machines, did computers borrow this process too ? Yep, they did ! Programmers had enough of hard manual work, repeating the same routines again and again... so they added looping !

 

Loops & MMB

 

ForNextLoopBottleStart

ForNextLoopBottle

ForNextLoopBottleEnd

 

That's how it's done in MMB ! Pour commands, just like syrup, until you have enough !

 

To use loops, you'll start by writing a For clause:

For

...adding a numerical variable that will be used as a counter:

Counter

...followed by equal sign:

=

...then writing starting value for a range of Counter variable :

1

...and adding To clause:

To

After this, you'll write an ending value of range for Counter variable:

100

Let's see now how the first for..next loop line looks like:

For Counter=1 To 100

 

Line above tells MMB that everything written below should be repeated. And how many times ? From the starting value of numerical variable, to an ending value of that variable.

After setting loop properties with code line above, you can start writing code lines that will be performed in the loop. In code sample above, commands would be executed 100 times (as specified through Counter numerical variable). So, let's write some already-known commands:

var$='Hello from loop, this is first message box'

Message("","var$")

var$='Hello from loop, this is second message box'

Message("","var$")

These lines will display two message boxes. One saying Hello from loop, this is first message box, and the second one saying Hello from loop, this is second message box . If these lines were executed without loop, message boxes would appear only once each. But ! Specifying loop using For Counter=1 To 100, we said to MMB: repeat showing these message boxes hundred times each ! Every var$ would be assigned 100 times. Every message box would appear 100 times.

Once you're done writing commands that should be executed in loop, it's necessary to mark the end of such code block, otherwise MMB wouldn't know what's inside and outside of the for..next loop. And running entire program in one big loop surely ain't something you want.

Marking the end of for..next loop code block is done using Next clause. Remember that numerical variable Counter, used for setting number of loop repeats ? You'll write label of that variable behind the Next clause:

Next Counter

It's like saying to MMB: once you're done performing lines in for..next block, update value of numerical variable used as a counter (it goes either +1 or -1, more about it below) and start performing block lines all over again !

Here's colorized summary of for..next loop code lines:

For Counter= 1 To 100

 var$='Hello from loop, this is first message box'

Message("","var$")

var$='Hello from loop, this is second message box'

Message("","var$")

Next Counter

Loop clauses For, To, Next are marked blue.

Numerical variable that serves as a loop counter is labeled Counter and is marked red.

Range for loop counter is marked green, in this case 0 - 100.

All code lines that are executed repeatedly in loop are pink - var$, Message("","")

Loop counter

If you stand by the road and count cars passing by, you'll start from the first car and think of number "1" . When another car passes by, you'll add 1 to previous number and keep waiting for the next car. Until you get bored and say: Hey, I had enough of this loop !

Another case is a stopwatch in one hand, a gun in another hand and dozen of racers on track at some big stadium. You count down numbers...

10...9...8...7...6...5...4...3...2...1...BANG !

 

Both cases are being used in MMB for..next loops for counting purposes. Already mentioned next clause does exactly what people do when counting things - it either adds 1 or substracts 1 to/from some number (represented as numerical variable). That way, MMB's numerical variable "remembers" number of repeats it performed on code block inside loop and once it reaches ending value of range - loop is over, and BANG is heard (just kidding).

 

ForNextLoopTextSample

 

Sample above uses numerical variable i as a counter. Loop code block is performed 5 times, and after that, MMB continues executing code lines below For..Next loop block. It means that message box saying "After-loop message! !" will not be displayed before loop block is performed n times (in this case - 5).

Counting cases above mention both positive (+1) and negative (-1) counting. Examples of positive counting have been used before, but here's another one:

For Love=1 To 10

var$='I love MMB'

Message("","var$")

Next Love

That's when you start with lower value (Love=1) and end with higher value (To 10).

Counting in opposite (negative, -1) direction can also be used:

For Seconds=10 To 1

var$='Woof !'

Message("","var$")

Next Seconds

Here you start with higher value (Seconds=10) and end with lower value (to 1).

MMB compares starting and ending value, automatically deciding in what direction should it go. Of course, it's not necessary to use number 1 as either starting or ending point:

For MileAge=90 To 100

var$='Almost there!'

Message("","var$")

Next MileAge

This example uses 90 as a loop starting value and 100 as an ending value. So how many times will loop code be repeated ? Yep ! 10 !

 

And it's not like you'll just use for..next loop to execute fixed code ! While MMB uses numerical variables for counters, and numerical variables can be used wherever you want in your code, current value of loop counter can be used for some dynamic actions.

 

It's like walking from one runner to another before the race, giving 'em t-shirt labels saying "You're number 1", "You're number 2", "You're number 23473"...

 

Let's take a look at loop code sample:

For Runner=1 To 10

var$='You are runner no. '+CHAR(Runner)

Message("","var$")

Next Runner

 

Loop above uses numerical variable Runner to execute some code lines 10 times.

Assigning of text to string variable var$ is interesting - it first sets text "You are runner no." and then uses CHAR function to convert current value of numerical variable Runner (used as a loop counter, remember ?) to act as a string, when + operator assigns it to var$ .

 

The result ? Loop will show message box 10 times, but contents will be adjusted according to current value of loop counter. So, message box will every time read different numerical value:

You are runner no. 1

You are runner no. 2

You are runner no. 3

You are runner no. 4

You are runner no. 5

You are runner no. 6

You are runner no. 7

You are runner no. 8

You are runner no. 9

You are runner no. 10

This ability is very useful for intensive processing of items, names, records, files... you only change index number and everything else goes through the same block of commands inside the loop. A true time saver - imagine writing & maintaining the same block of commands for every item you want to process ! When you get into using loops, you will never throw 'em away ;)

TIP! There is also an option to dynamically change the To ending value from within the For..Next loop counter. Thanks to this you can prematurely terminate the For..Next loop in a certain conditions and without the need to call Return() or Break() function.

EXAMPLE OF USAGE:

The below script script is useless, but it can show you how to dynamically change the To value in For...Next loop. Initially, the loop should be repeated 5 times, but after the third loop, the loop range is changed to 3 and therefore the For..Next is terminated.

**This loop is terminated after 3 loops...

maxloop=5

For i=1 To maxloop

Message("in loop","")

If (i=3) Then

  ** maxloop is now 3!!

  maxloop=i

End

Next i

Message("outside loop","")

Loop utilities

Once in a while it's possible to have a need for an endless loop that will, for example, check some things (system info, file existence, user input...) occasionally and without specific number of repeats. That's when Infinite loops come into action:

For check=1 To Infinity

check=check+1

DisplayValue("Text","check")

Next check

Code sample above uses Infinity clause as an ending value of numerical variable counter, thus making definition of loop saying "Start with 1 and never stop" . Of course, that never is hypothetical - loop is repeated while your program is running and project page is not changed. If either user exits program, changes page or computer shuts program down, loop will reach the very end of it's infinity ;)

Issue emerging from using this kind of loops is - program functioning while such loop is being performed. Will everything be blocked while infinity loop keeps repeating ?

 

Not really, but to allow other objects & scripts to work properly it is recommended to use flow commands:

Refresh() - gives time to other threads being used by program to perform their actions

Pause("") - stops execution of code block for specified amount of time (in msecs)

Read more about these in command descriptions, here's how they work for loops:

For check=1 To Infinity

check=check+1

DisplayValue("Text","check")

Refresh()

Next check

 

Put after loop code block, Refresh() gives time to other program threads before starting another repetition of code block.

 

For check=1 To Infinity

check=check+1

DisplayValue("Text","check")

Pause("500")

Next check

Put after loop code block, Pause("500") makes delay (in this case 500 miliseconds - half a second) before repeating code block. It means that loop code will be executed every half a second. Even higher delay periods are recommended for tasks where real-time check-ups are not of a critical importance.

Another issue related to infinity loops in service of check-ups is a case when some condition has been fulfilled and loop should be stopped. In that case Return() command is a great help, while it stops further execution of entire script:

For check=1 To Infinity

check=check+1

DisplayValue("Text","check")

If (UserInput$='GO') Then

  Return()

End

Pause("500")

Next check

In case you don't want to stop execution of entire script, but only jump from the current For..Next loop, use Break() command instead. The execution of code will continue after "Next n" line of the For..Next loop where the Break() function was used.

Loop above is "smart" enough to perform repetition as long as value of string variable UserInput$ doesn't match fixed value "GO" . When UserInput$ contains correct value, if statement will call Return() command and loop (together with any code lines below the loop block) will be stopped. This routine is oftenly being used to call some other script with RunScript and ScriptTimer commands:

For check=1 To Infinity

check=check+1

DisplayValue("Text","check")

If (UserInput$='GO') Then

  RunScript("InputCorrect")

  Return()

End

Pause("500")

Next check

Read more about RunScript and ScriptTimer in their command descriptions.

That's about everything to tell on the loop subject ! If you're a beginner in MMB scripting, loops probably won't be the first subject you'll get into, and instead you'll use manual code repetitions. But as you make progress in MMB scripting learning curve, loops will come up as a very comfortable solution for tasks with intensive scripting.