For variable = start To limit [Step increment]
Parameters
|
variable - the loop counter; must be an integer or float variable, and cannot be a constant start - the value the counter begins at limit - the last value the counter is allowed to reach; the loop body still runs on that value increment (optional) - amount added to the counter each pass; must be a constant, 1 (default) |
Description
|
Runs a block of code once for each value in a range. For is the counted loop, and it always ends with Next. Every pass adds the step to the counter and re-tests it, so this fills a row of ten tiles: For x = 0 To 9 DrawImage tile, x*32, 0 Next Count backwards with a negative Step, and use a float counter when you want fractions: For a# = 0 To 1 Step 0.1 works fine, the counter just has to be an integer or a float variable - a string or a custom Type will not compile. The other shape is For Each, which walks every object of a custom Type instead of a number range. Same For, same Next, different job. Two things catch people out. The test happens before the first pass, so For i = 1 To 0 runs zero times rather than once. And the limit is re-evaluated on every pass, so For i = 0 To CountObjects() calls that function every single time round - work it out once into a variable first if it is expensive. The step must be a constant. For i = 0 To 100 Step n is a compile error ("Step value must be constant"), because the compiler decides at build time whether the loop counts up or down. If you need a variable stride, use a While loop and add it yourself. Unlike most BASICs, Next takes no variable name - write Next, never Next i. Nested loops match up automatically, innermost first, and Exit leaves one level. See also: To, Step, Next, Each, Exit, While. |
Example
; For Example ; ----------- ; For repeats its block once for each value of the counter variable Print "Launch checklist:" For stage=1 To 5 Print " Stage "+stage+" ... check!" Next Print "" ; Counting down works too, with a negative Step Print "Countdown:" For count=5 To 1 Step -1 Print " "+count+" ..." Next Print " Lift off!" Print "" Print "Press any key to close the example" WaitKey End
Index