Sie sind auf Seite 1von 16

WML Script

WMLScript (Wireless Markup Language Script) is the client-side scripting language of


WML (Wireless Markup Language). A scripting language is similar to a programming
language, but is of lighter weight. With WMLScript, the wireless device can do some of
the processing and computation. This reduces the number of requests and responses
to/from the server.
This chapter will give brief description of all the important WML Script components.
WML Script Components:
WML Script is very similar to Java Script. Almost WML Script components have similar
meaning as they have in Java Script. A WML Script program components are
summarized as follows:
WML Script Operators:
WML Script supports following type of operators.
Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators
Check for complete detail of The WML Operators.
WML Script Control Statements:
Control statements are used for controlling the sequence and iterations in a program.
Statement Description
if-else Conditional branching
for Making self-incremented fixed iteration loop
while Making variable iteration loop
break Terminates a loop
continue Quit the current iteration of a loop
Check for complete detail of WML Script Control Statements.
WML Script Functions:
The user-defined functions are declared in a separate file having the extension .wmls.
Functions are declared as follows:
function name (parameters)
{
control statements;
return var;
}
The functions used are stored in a separate file with the extension .wmls. The functions
are called as the filename followed by a hash, followed by the function name:
maths.wmls#squar()
WML Scripts Standard Libraries:
There are six standard libraries totally. Here is an overview of them:
Lang: The Lang library provides functions related to the WMLScript language core.
Example Function: abs(),abort(), characterSet(),float(), isFloat(), isInt(), max(), isMax(),
min(), minInt(), maxInt(), parseFloat(), parseInt(), random(), seed()
Float: The Float library contains functions that help us perform floating-point arithmetic
operations.
Example Function: sqrt(), round(), pow(), ceil(), floor(), int(), maxFloat(), minFloat()
String: The String library provides a number of functions that help us manipulate
strings.
Example Function: length(), charAt(), find(), replace(), trim(), compare(), format(),
isEmpty(), squeeze(), toString(), elementAt(), elements(), insertAt(), removeAt(),
replaceAt()
URL: The URL library contains functions that help us manipulate URLs.
Example Function: getPath(), getReferer(), getHost(), getBase(), escapeString(),
isValid(), loadString(), resolve(), unescapeString(), getFragment()
WMLBrowser: The WMLBrowser library provides a group of functions to control the
WML browser or to get information from it.
Example Function: go(), prev(), next(), getCurrentCard(), refresh(), getVar(), setVar()
Dialogs: The Dialogs library Contains the user interface functions.
Example Function: prompt(), confirm(), alert()
WML Scripts Comments:
There are two types of comments in WMLScript:
Single-line comment: To add a single-line comment, begin a line of text with the //
characters.
Multi-line comment: To add a multi-line comment, enclose the text within /* and */.
These rules are the same in WMLScript, JavaScript, Java, and C++. The WMLScript
engine will ignore all comments. The following WMLScript example demonstrates the
use of comments:
// This is a single-line comment.

/* This is a
multi-line comment. */

/* A multi-line comment can be placed on a single line. */
WML Script Case Sensitivity:
The WMLScript language is case-sensitive. For example, a WMLScript function with the
name WMLScript Function is different from wmlscript function. So, be careful of the
capitalization when defining or referring to a function or a variable in WMLScript.
Whitespaces in WMLScript:
Except in string literals, WMLScript ignores extra whitespaces like spaces, tabs and
newlines. Hence, the code in the earlier "Hello World" example can be typed in the
following way and the result will remain the same:
Arithmatic Operators:
There are following arithmatic operators supported by WML Script language:
Assume variable A holds 10 and variable holds 20 then:
Operator Description Example
+ Adds two operands A + B will give 30
- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
%
Modulus Operator and remainder of after
an integer division
B % A will give 0
++
Increment operator, increases integer value
by one
A++ will give 11
--
Decrement operator, decreases integer
value by one
A-- will give 9
Comparison Operators:
There are following comparision operators supported by WML Script language
Assume variable A holds 10 and variable holds 20 then:
Operator Description Example
==
Checks if the value of two operands is
equal or not, if yes then condition becomes
true.
(A == B) is not true.
!=
Checks if the value of two operands is
equal or not, if values are not equal then
condition becomes true.
(A != B) is true.
>
Checks if the value of left operand is
greater than the value of right operand, if
yes then condition becomes true.
(A > B) is not true.
<
Checks if the value of left operand is less
than the value of right operand, if yes then
condition becomes true.
(A < B) is true.
>=
Checks if the value of left operand is
greater than or equal to the value of right
operand, if yes then condition becomes
true.
(A >= B) is not true.
<=
Checks if the value of left operand is less
than or equal to the value of right operand,
if yes then condition becomes true.
(A <= B) is true.
Logical Operators:
There are following logical operators supported by WML Script language
Assume variable A holds 10 and variable holds 20 then:
Operator Description Example
and
Called Logical AND operator. If both the
operands are true then condition becomes
true.
(A and B) is true.
or
Called Logical OR Operator. If any of the
two operands is non zero then condition
becomes true.
(A or B) is true.
&&
Called Logical AND operator. If both the
operands are non zero then condition
becomes true.
(A && B) is true.
||
Called Logical OR Operator. If any of the
two operands is non zero then condition
becomes true.
(A || B) is true.
!
Called Logical NOT Operator. Use to
reverses the logical state of its operand. If
a condition is true then Logical NOT
operator will make false.
!(A && B) is false.
Assignment Operators:
There are following assignment operators supported by WML Script language:
Operator Description Example
=
Simple assignment operator, Assigns
values from right side operands to left
side operand
C = A + B will assigne value of A + B into C
+=
AND assignment operator, It adds
right operand to the left operand and
assign the result to left operand
C += A is equivalent to C = C + A
-=
Subtract AND assignment operator, It
subtracts right operand from the left
operand and assign the result to left
operand
C -= A is equivalent to C = C - A
*=
Multiply AND assignment operator, It
multiplies right operand with the left
operand and assign the result to left
operand
C *= A is equivalent to C = C * A
/=
Divide AND assignment operator, It
divides left operand with the right
operand and assign the result to left
operand
C /= A is equivalent to C = C / A
%=
Modulus AND assignment operator, It
takes modulus using two operands
and assign the result to left operand
C %= A is equivalent to C = C % A
Conditional Operator
There is one more oprator called conditional operator. This first evaluates an expression
for a true or false value and then execute one of the two given statements depending
upon the result of the evaluation. The conditioanl operator has this syntax:
Operator Description Example
? : Conditional Expression
If Condition is true ? Then value X : Otherwise
value Y
Operators Categories:
All the operators we have discussed above can be categorised into following categories:
Unary prefix operators, which precede a single operand.
Binary operators, which take two operands and perform a variety of arithmetic and
logical operations.
The conditional operator (a ternary operator), which takes three operands and evaluates
either the second or third expression, depending on the evaluation of the first
expression.
Assignment operators, which assign a value to a variable.
Precedence of WML Script Operators:
Operator precedence determines the grouping of terms in an expression. This affects
how an expression is evaluated. Certain operators have higher precedence than others;
for example, the multiplication operator has higher precedence than the addition
operator:
For example, x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedenace than + so it first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedenace operators
will be evaluated first.
Category Operator Associativity
Unary ! ++ -- Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= Right to left

WML Script if...else Statement:
WMLScript's if statement uses the following syntax. The part inside brackets [] is optional. The
syntax is the same as that of C++, Java and JavaScript.
if (condition)
{
WMLScript statement(s)
}
[else
{
WMLScript statement(s)
}]
If condition is the Boolean value true, the statement(s) enclosed in the first curly brackets {} will
be executed; if condition is false or invalid, the statement(s) enclosed in the second curly
brackets {} will be executed.
WML Script while Statement
WMLScript's while statement is used to repeat the execution of a block of statements while a
condition is true. It has the following syntax:
while (condition)
{
WMLScript statement(s)
}
The statement(s) enclosed in the curly brackets {} will be executed again and again as long as
condition is true. The loop stops when condition evaluates to false or invalid.
WML Script for Statement
Like a while loop, a for loop is executed repeatedly as long as a condition is satisfied. If the
number of times to be repeated is certain, using the for statement will be more convenient than
using the while statement. The for statement has the following syntax in WMLScript. The parts
enclosed in brackets [] are optional.
for ([expression1]; [expression2]; [expression3])
{
WMLScript statement(s)
}
expression1 is the initialization expression. It is executed before any WMLScript statements in
the for loop are executed. expression1 is executed once only in the lifetime of the for statement.
expression2 is the conditional expression that determines whether the for loop should continue or
stop. expression3 is executed after each iteration.
WML Script break Statement
The break statement is used to quit a loop. It must be put inside while loops or for loops. The
following WMLScript example demonstrates how to use the break statement:
var result = 0;
for (var counter=0; counter<10; counter++)
{
break;
result += 5;
}
After the execution the above WMLScript code, the value of result is 0. This is because the break
statement exits the for loop. The statement "result += 5;" is never executed.
WML Script continue Statement
The continue statement is used to quit the current iteration of a loop in WMLScript. The next
iteration will be started if the loop's conditional expression evaluates to true. The continue
statement must be put inside while loops or for loops. The following script demonstrates how to
use the continue statement:
var result1 = 0;
var result2 = 0;
for (var counter=0; counter<10; counter++)
{
result1 += 5;
continue;
result2 += 5;
}
After the execution of the above WMLScript code, the value of result1 is 20 and that of result2 is
0. This is because when the WMLScript interpreter encounters the continue statement, it will end
the current iteration. Hence, the statement "result2 += 5;" is never executed.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd">

<wml>
<card id="card1" title="WMLScript Tutorial">
<p>
<a href="helloWorldEg1.wmls#helloWorld()">Run WMLScript</a><br/>
$(message)
</p>
</card>
</wml>

Here is the file that contains the WMLScript code:

(helloWorldEg1.wmls)
extern function helloWorld()
{
WMLBrowser.setVar("message", "Hello World. Welcome to our WMLScript tutorial.");
WMLBrowser.refresh();
}
WMLBrowser.setVar("message", "Hello World. Welcome to our WMLScript tutorial.");
WMLBrowser.refresh();

to refresh the WML card so that the change made to the message variable is shown on the screen
of the mobile device.
To call the WMLScript function helloWorld() in the WML document, we use the URL below:

helloWorldEg1.wmls#helloWorld()

In WMLScript, all code must be encapsulated in functions. This is different from JavaScript in
which a web developer can choose whether to place the code in functions or directly in the
markup. A function in WMLScript is defined using the following format. The parts enclosed
inside brackets [] are optional.

[extern] function function_name([argument1, argument2...])
{
WMLScript statements here
[return (some_value);]
}

The extern Keyword
The extern keyword is used to specify that a function can be called from both inside and outside
of the WMLScript file, i.e. the function can be called from functions in the same WMLScript
file, from functions in a different WMLScript file, or in a WML file. If you define a function
without the extern keyword, the function can only be called from functions in the same
WMLScript file.

WMLScript Function Naming Conventions
In WMLScript, function names must be started with a letter or an underscore character. The rest
of the characters can be letters, numbers, or underscores. Special characters other than the
underscore are not permitted. You cannot use WMLScript reserved words and keywords as
function names. Remember that WMLScript is case-sensitive. The names wmlscript_function
and WMLScript_Function refer to two different functions.
Here are some examples of valid function names:
wmlscriptFunction
_wmlscript_function
wmlscript_function1
wmlscript_1st_function
WMLSCRIPT_FUNCTION
____________
And here are some examples of invalid function names:
1st_wmlscript_function (Reason: you cannot start a function name with a number)
11111 (Reason: You cannot start a function name with a number)
wmlscript-function (Reason: The - character is not permitted)
~wmlscript_function (Reason: The ~ character is not permitted)

WMLScript Function Arguments
Arguments are used to pass values into a function. Unlike programming languages like C++ or
Java, WMLScript does not require you to specify the data type of an argument. For example, to
pass two numbers into the WMLScript function wmlscript_function(), you will define something
like this:

function wmlscript_function(number1, number2)
{
...
}

If a function does not require any arguments, you still need to include the parentheses (), like
this:

function wmlscript_function()
{
...
}

The return Statement
The "return (some_value);" statement is used to return a value back to the calling function in
WMLScript. For example, the calculateSum() function below returns the sum of two numbers
back to the calling function each time it is executed:

function calculateSum(number1, number2)
{
return (number1 + number2);
}

The wmlscript_function() function below calls calculateSum() with two arguments 1 and 2. The
value 3 is returned from calculateSum() and is assigned to the sum variable:

function wmlscript_function()
{
...
sum = calculateSum(1, 2);
...
}

It is not a must to include a return statement in a WMLScript function. If no return statement is
included, the default value, which is an empty string, will be returned.

he URL can be in absolute or relative form.
The following example demonstrates how to use anchor links to call WMLScript functions from
a WML card. Suppose we have a WMLScript file called wmlscript.wmls, which contains the
following script:

extern function wmlscript_function()
{
WMLBrowser.setVar("message", "Welcome to our WMLScript tutorial");
}

To call wmlscript_function() from a WML card, create an anchor link using the following WML
markup. The script will be executed if you click the anchor link.

<a href="wmlscript.wmls#wmlscript_function()">Execute Script</a>

Or

<anchor>
<go href="wmlscript.wmls#wmlscript_function()"/>
Execute Script
</anchor>

Another way to call wmlscript_function() in a WML card is to place the URL in a WML event
handler. The script will be executed when the WML event occurs. For example, the following
markup instructs the WAP browser to call wmlscript_function() when the ontimer event is
triggered:

<onevent type="ontimer">
<go href="wmlscript.wmls#wmlscript_function()"/>
</onevent>
<timer value="50"/>

Four event types are supported in WML. They are ontimer, onenterbackward, onenterforward
and onpick. Details about them can be found in the "WML Events and the <onevent> Tag"
section of our WML tutorial.

Passing Arguments to Functions
The wmlscript_function() function above does not take any arguments. Now let's see how to pass
arguments to functions. Suppose there is another function called addition() that takes two
numbers as its arguments:

extern function addition(number1, number2)
{
WMLBrowser.setVar("message", number1 + number2);
}

To call addition() from a WML card, we need to include two arguments in the URL. For
example, to pass two integers 10 and 11 to addition(), we can make use of the following WML
markup:

<a href="wmlscript.wmls#addition(10, 11)">Execute Script</a>

In some situations, what you want to pass into a WMLScript function is not a fixed value but is a
WML variable. The following WML markup demonstrates how to pass two WML variables,
wmlVar1 and wmlVar2, to the addition() function:

<card id="card1" title="WMLScript Tutorial">
<onevent type="onenterforward">
<refresh>
<setvar name="wmlVar1" value="10"/>
<setvar name="wmlVar2" value="11"/>
</refresh>
</onevent>

<p>
<a href="wmlscript.wmls#addition($(wmlVar1), $(wmlVar2))">Execute Script</a>
</p>

...
</card>

When the WAP browser comes across the terms $(wmlVar1) and $(wmlVar2), it will substitute
them with their stored value. So, the WML markup:

<a href="wmlscript.wmls#addition($(wmlVar1), $(wmlVar2))">Execute Script</a>

will become:

<a href="wmlscript.wmls#addition(10, 11)">Execute Script</a>

Note that if the value of wmlVar1 and wmlVar2 contains non-numeric characters, $(wmlVar1)
and $(wmlVar2) have to be enclosed in quotes so that the values are passed into the function as
string literals, like this:

<a href="wmlscript.wmls#addition('$(wmlVar1)', '$(wmlVar2)')">Execute Script</a>

Suppose the values of wmlVar1 and wmlVar2 are still 10 and 11 respectively. After substitution,
the above WML markup will become:

<a href="wmlscript.wmls#addition('10', '11')">Execute Script</a>

WMLScript variables are actually handled as five primitive data types internally. A variable can
be used to store a value of any of the five primitive data types. The data types supported in
WMLScript are:

1. Boolean. A Boolean value can be true or false.
Examples:
var variable1 = true;
var variable2 = false;

2. Integer. WMLScript uses 32-bit integers with two's complement. This means an integer value
can be in the range from -2
32
/2 to 2
32
/2-1, i.e. -2147483648 to 2147483647.
Examples:
var variable1 = 10000;
var variable2 = -10000;

3. Float. WMLScript uses 32-bit single precision format to represent floating-point numbers. The
maximum value supported is 3.40282347E+38. The smallest positive nonzero value supported is
1.17549435E-38. Note that some mobile devices do not support floating-point numbers. The
float() function of WMLScript's Lang standard library can be used to check whether a mobile
device supports floating-point numbers.
Examples:
var variable1 = 11.11;
var variable2 = -11.11;

4. String. A string contains some characters.
Example:
var variable = "WMLScript Tutorial";

5. Invalid. This is used to indicate that a variable is invalid.
Example:
var variable = invalid;

Sometimes the result of an operation is of the invalid type. This means errors have occurred
during the operation. One example is the divide-by-zero error:

var variable = 100 / 0;

Using WMLScript to Obtain the Value of a WML Variable
WMLScript's getVar() function helps you obtain the value of a WML variable. It is used in the
following form:

WMLBrowser.getVar(variable_name);

variable_name is the name of a WML variable.
The getVar() function returns:
a string containing the value stored in the WML variable variable_name if the function
call succeeds
an empty string if the WML variable variable_name does not exist
invalid if variable_name is of the wrong syntax, e.g. variable_name contains characters
that are not allowed to appear in WML variable names.
Here is an example demonstrating how to use the getVar() function:
var wmlscript_variable = WMLBrowser.getVar("message");

When the WMLScript interpreter encounters the above line of script, the value of the WML
variable message is assigned to the WMLScript variable wmlscript_variable.

Das könnte Ihnen auch gefallen