O'Reilly logo

Learning WML, and WMLScript by Martin Frost

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Loops

As well as conditions with if and else, WMLScript provides looping constructs. There are two types: for and while. Both behave very much as they do in C.

A while loop executes its body while a condition is true. If the condition is false at the start, the body is never executed. (As with if, failure to convert to Boolean is taken as false.) It looks like:

while (condition) body

For example:

while (n > 1) {
    total *= n;
    --n;
}

A for loop is much more flexible and powerful. It looks like:

for (initializer; condition; increment) body

First, the optional initializer is evaluated as an expression. Instead of simply initializing a variable that was previously declared:

for (i=0; i<count; i++)

you can declare the variable in the initializer as well:

for (var i=0; i<count; i++)

The body is then executed while the condition can be converted to Boolean true. (As with while, if the condition isn’t true at the start, the body never gets executed.) The condition may also be omitted, in which case it’s taken as being always true, so the loop runs forever unless something happens in the body to stop it.

After each execution of the body, the increment expression is evaluated as an expression statement. As with the initializer and condition, it may be omitted, in which case it’s simply ignored.

It’s good style to use a for loop when the loop runs over a fixed set of values, such as a range of integers or for the elements in a list, with a single variable tracking your progress through the set. Set up ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required