Statements

From Pengower
Jump to: navigation, search

Learn different scripting statements and use them on your application.

Control Flow: If, For, Loop Statements


If / Else / EndIf Statement

The ‘If / Else / EndIf’ statement provides the means by which branching or decisions are taken within ActionScript, i.e. different blocks of statements will be executed dependent on the value of a conditional expression. The available syntaxes for the ‘If / Else / EndIf’ statement are:

If <conditional_expression>
	<block_of_statements>
EndIf

and

If <conditional_expression>
	<block_of_statements>
Else
	<block_of_statements>
EndIf

These are demonstrated in the code below;

If (x > 3)
	Report = " – X is larger than 3"
	Output = person
	Return_Ok
EndIf
If ((x > 3) And (y < 2))
	Set z = 1
Else
	Set z = 0
EndIf

Key to the usage of the ‘If’ statement is an understanding of the conditional operators supported by ActionScript.


Conditional Operators


Action Script supports the following the following conditional operators:

‘>’ – greater than, e.g. (x > 3), ‘x’ is greater than ‘3’? This will return TRUE (1) if x is greater 3 or FALSE (0) if x is equal to or less than 3.

‘<’ – less than, e.g. (x < 3), ‘x’ is less than ‘3’? This will return TRUE if x is less than 3 and FALSE otherwise.

‘=’ – equal to, e.g. (x = 3), ‘x’ is equal to ‘3’? This will return TRUE if x equals 3 and FALSE otherwise.

‘!=’ – not equal to, e.g. ( x != 3). ‘x’ is not equal to ‘3’? This will return TRUE if x equals any value but 3 and FALSE otherwise.

In addition ActionScript also supports the two Boolean operators ‘And’ and ‘Or’. These can be used to combine simple conditional expressions to form a larger more complex expression.

When using ‘And’ both conditional expressions on either side of the ‘And’ must evaluate to TRUE for the expression as a whole to evaluate to TRUE. In the case of the ‘Or’ operator either expression on either side of the operator can evaluate to TRUE and the whole expression will evaluate to TRUE.

Examples of the use of Boolean operators in Action Script are given below;

Set x = 1
Set y = 1
Set z = 0

If ((x > 0) And (y < 0))
	// these statements won’t be executed
	Set z = z + 1
EndIf

If ((x > 0) Or (y < 0))
	// these statements will be executed
	Set z = z + 1
EndIf

Output = z
Return_Ok

Nesting If Statements 


Within ActionScript it is possible to nest ‘If’ blocks. That is one ‘If’ block can completely enclose another ‘If’ block. Examples of valid nesting of ‘If’ blocks are shown below:

Set z = 0
If (x > 2)
	Set y = y + x
	
	If (y > 4)
		Set z = 2
	EndIf
	
	If ((y > 4) And (x > 5))
		Set z = 4
	EndIf

Else
	If ( y < 4)
		If (q = 2)
			Set z = 10
		EndIf
	EndIf
EndIf

Notice that nested loops can go more than one layer deep.



For / Next Statement

The ‘For/Next’ statement allows a block of statements to be executed a set number of times dependent on the value of another variable. This is also known as a For Loop.


Basic Example

The basic syntax for the ‘For/Next’ statement is:

For [var] = [var] To [var]
    [block_of_statements]
Next

Examples of valid syntax for the ‘For/Next’ statement are shown below:

For j = 1 To array.Count
    Set item = array[j]
    Do Store Item Params Item = item
Next

In the example above the variable (or counter) j will initially be set to 1 and for each loop it will increase by 1 until it is equal to the value of array.Count, where it will execute the final loop.

i.e. For j = 1 To 5 is the equivalent of "Repeat until j is more than 5."


Nested Example

For Loops can also be used from inside another For Loop. This is known as a Nested For Loop. The parameters for the inner loop can also be dependant on the outer loop. In the example below the inner loop will execute depending on the value of j in the outer loop.

For j = 1 To array.Count 
    Set arr = {} 
	
    For k = 1 To j 
        Set x = j * k 
        Add x To arr 
    Next 
Next



Loop/Until Statement

The ‘Loop/Until’ statement allows a block of statements to be executed a set number of times dependent on the value of another variable.


Basic Example

The basic syntax for the ‘Loop/Until’ statement is:

Loop
	[block_of_statements]
Until ([Condition to end the loop])

Examples of valid syntax for the ‘Loop/Until’ statement are shown below;

Set j = 1
Set outputString = ""
Loop
	Set outputString = outputString + j + " "
	Set j = j + 1
Until (j = 5)
Output = outputString
Return_Ok

Will give the result: "1 2 3 4 5"

It is important to note the variable j is defined outside of the loop and is incremented within the loop. See other differences between For / Next and Loop / Until.

N.B. - you MUST include a condition that will be met or the loop will not end. In a standard script you will then have to wait for a timeout, In a Long Run Script you will have to manually cancel.


Nested Example

Loop Untils can also be used from inside another Loop. This is known as a Nested Loop. The parameters for the inner loop can also be dependant on the outer loop. In the example below the inner loop will execute depending on the value of j in the outer loop.

Set j = 1
Set outputString = ""
Loop
	Set k = 1
	Set outputString = outputString "("+ j + ") "
	Loop
		Set outputString = outputString + k + " "
		Set k = k + 1
	Until (k = j)
	Set j = j + 1
Until (j = 5)
Output = outputString
Return_Ok

Will give the result: "(1) 1 (2) 1 2 (3) 1 2 3 (4) 1 2 3 4 (5) 1 2 3 4 5"


Differences between For / Next and Loop / Until

  • Loop / Until will always execute once, For / Next will not run if the initial value of the counter is greater than the To value.
  • Loop / Until Requires a variable to be defined before the Loop, For / Next defines a variable at the start of the loop.
  • Loop / Until Requires manual incrementing of the variable, For / Next does this after each loop.


Comment Statement

The comment statement simply allows for the inclusion of developer notes within the script and will be ignored during execution. Each comment is limited to a single line. The syntax for comments is;

// This is a comment


Set Statement

The Set statement allows for the declaration of and assignment to variables. There are four possible syntactic variations;

Set [va] = [expression]
Set [var] = [do_command]
Set [var] = [get_command]
Set [var] = {[var], [var] … }

where [var] represents a variable being declared and assigned to or simply assigned to. Examples of valid Set statements are;

Set x = 2 + 3 + y
Set y = y + 1
Set arr = {1, 2, 3}
Set outStr = "Hello World. The answer is " + ans


Do Statement

The ‘Do’ statement is the mechanism through which more complex pre-defined commands are accessed.

In order to keep ActionScript relatively simple the syntax has been kept to a minimum, unfortunately this means that it is not possible to perform the full range of actions that would be desirable when writing scripts. In order to circumvent this issue a library of more complex script actions has been produced to enable the developer to write more functionally rich scripts. These script actions are accessed through the ‘Do’ command syntax.

The underlying architecture of ActionScript has been developed such that the range of script actions available via the ‘Do’ command can be rapidly extended as the demands of developers increase.

There are 2 basic syntaxes for the ‘Do’ command, these are;

Do [script action name] Params [script action arguments]

and

Set [var] = Do [script action name] Params [script action arguments]

The flavour used will depend on whether the ‘Do’ command chosen provides a return variable. The definitions below show which script actions return a variable.

A typical example of a script action called via a ‘Do’ command that returns a variable is the ‘New Object’ action. An example of the syntax for the ‘New Object’ action is;

Set person = Do New Object Params Type = "Person"

A typical example of a script action that doesn’t return a variable is the ‘Store Item’ action. An example of the syntax for the ‘Store Item’ action is;

Do Store Item Params Item = person

All the script actions accessible via the ‘Do’ command follow these basic syntactic patterns. A full list of the currently available script actions can be found in the Do Statement Library. Note, as the platform has been developed to allow addition of more script actions over time the list below should not be considered definitive. Regular updates to this manual will be provided showing new script actions as the library is extended.

AddTo Statement

String Builder is a method of constructing strings at a much faster pace, allowing performance advantages. It is especially useful for long strings, such as constructing HTML and Javascript.

Using the String Builder

Set string = Do New String Builder
Set myColour= "red"
AddTo string = "<span style = 'color:" + myColour + ";' >"
AddTo string = "Span contents go here"
AddTo string = "</span>"
Set string = "" + string
Output = string
Return_Ok

Note, string builders have to be finalised by forcing them into a string before they can be used inside ActionScript:

Set string = "" + string


Get Statement

The ‘Get’ statement is the primary mechanism for extracting data from the underlying database for use within scripts. The ‘Get’ statement has 5 basic forms;

  1. Set [var] = Get "[type name]"
  2. Set [var] = Get "[group name]"
  3. Set [var] = Get "Current_Selection"
  4. Set [var] = Get "[type name]" Where [index name] {=|>|<|!=|~|>=|<=} [var]|[literal] {&|’|’} …
  5. Set [var] = Get "[type name]" Where [string var]

Each of these syntaxes is explained below.

(i) Set [var] = Get "[type name]" A simple mechanism for getting all instances of a type currently stored in the database. The returned variable will be an array containing a collection of item variables.

Example:

Set arr = Get "Pet"
Set outstr = "Pet names; "
For j = 1 To arr.Count
     Set pet = arr[j]
     Set outstr = outstr + pet["Name"] + ", "
Next
Output = outstr
Return_Ok

(ii) Set [var] = Get "[group name]" A mechanism for accessing the members of a pre-defined Group. Groups are defined elsewhere within the application builder and can then be accessed in script as required. The return will once again be an array of item variables.

Example(a group exists called ‘Dogs’ that filters pets according to ‘Type’ = "Dog"):

Set dogs = Get "Dogs"

(iii) Set [var] = Get "Current_Selection"

This construct is used in conjunction with listing pages to extract a selection made by the end user. On listing pages the user has the option to select a number of items and then call an action to utilise the selection. This form of the command will return an array containing item variable representing the user selection.

Example:

Set pets = Get "Current_Selection"
For j = 1 To pets.Count
     Set pet = pets[j]
     …
Next

(iv) Set [var] = Get "[type name]" Where [index name] {=|>|<|!=|~|>=|<=} [var]|[literal] {&|’|’} …

  • The query statement can only include those elements of the type that have been included in the index structure of the type. This is to ensure the performance of ActionScript is maintained.
  • The query statement can include the following operators;
    • = - equal to
    • > - greater than
    • < - less than
    •  != - not equal to
    • ~ - like, should be used in conjunction with the wild card character ‘%’ for partial string matching
    • >= - greater than or equal to
    • <= - less than or equal to
  • The query statement can also include the Boolean operators ‘&’ and ‘|’. ‘&’ represents the Boolean ‘And’ operator, whilst ‘|’ represents the Boolean ‘Or’ operator.
  • Query statements cannot include brackets. To use brackets to form more complex expressions see variant (v).

Note, the ‘~’ operator works in conjunction with the wild card character ‘%’ to enable partial string matching. This allows constructs such as ‘Surname~"D%"’ to find all instances of a type where the ‘Surname’ begins with ‘D’. It can also be used to handle cases where the input may or may not start with a capital letter, e.g. ‘Name~"%icrosoft"’ which will match both ‘Microsoft’ and ‘microsoft’.

The ‘%’ character is the general wild card that can match against one or more characters. The ‘_’ is the single character wild card that will match against only one character.

Examples:

Set expDogs = Get "Pet" Where Type = "Dog" & Value > 500
Set ds = Get "Person" Where Surname ~ "D%" | Surname ~"d%"

(v) Set [var] = Get "[type name]" Where [string var]

  • This is the most general form of the ‘Get’ statement. The ‘[string var] will be interpreted as a conditional expression as with option (iv) and will produce and array of item variables of the given Type matching the query expression.
  • The query expression can include all the conditional operators outlined in option (iv).
  • The query expression can include brackets to form more complex constructs.
  • The query expression can only relate to those elements that are included in the index structure of the type.
  • If you wish you can also compare two indexes within the expression, e.g. "First Name = Known As Name"
  • When you wish to include string literals with the expression they should be placed within single quotes, e.g. "Surname = ‘Jones’"
  • Dates and Time Periods need to be represented in a special fashion. Dates can either be represented as a simple date (no time component) or as a point in time that includes both date and time information. The syntax for a simple date is; "DATE ‘yyyy-mm-dd’". For a point in time the syntax is; "POINT ‘yyyy-mm-dd hh:mm’". For Time Periods the syntax is "PERIOD ‘dddd:hh:mm:ss’" where ‘dddd’ represents the number of days in the period. A time can also be represented using "TIME ‘hh:mm’".

Examples:

Set sql = "((Surname ~ ‘D%’ & DOB > DATE ‘1970-01-01’) | (First Name = ‘" + fname + "’))"
Set arr = Get "Person" Where sql
Output = arr.Count
Return_Ok

WARNING: When building the index structure of a type that you intend to interrogate via script it is important that no single index element name is an exact sub-set of another index e.g. it would be incorrect to have indexes ‘First Name’ and ‘Name’, as this will cause script ‘Get’ errors.

When building the SQL statement in script care must be taken if the syntax includes a single quote – e.g. looking for somebody called O’Hare. In this case the single quote should be replaced by two single quotes to allow the SQL to execute correctly. See the example below…

Set sql = "Surname = ‘O’’Hare’ & First Name = ‘Peter’"
Set arr = Get Person Where sql
Output = arr
Return_Ok


Ordering

Outputs can be ordered by one or multiple fields by using the ORDER BY [Field Name] ASC/DESC extension on the Get statement.

Multiple fields must be separated with a comma, in the format: [Field Name 1] ASC/DESC, [Field Name 2] ASC/DESC, [Field Name 3] ASC/DESC, etc.

For example:

Set objType = "Staff Record"
Set sql = "Contact = '" + objType + "' ORDER BY Colour ASC, Name ASC"
Set expenseTypes = Get "Expense Type" Where sql

This will get all of the Expense Types for a Staff Record which is ordered by the Colour field and then by the Name field.

NOTE: This must be placed in the same variable that holds the statement for the Where clause.


Return Statement

The ‘Return_Ok’ statement

The ‘Return_Ok’ statement is used to terminate execution of the script and return the ‘NO ERROR’ indicator to the script engine. It can be placed anywhere within the script and a single script can contain any number of ‘Return_Ok’ statements.

Example:

Set x = 5
Return_Ok


The 'Return_Error' Statement

The ‘Return_Error’ statement is used to terminate execution of the script and return the ‘ERROR’ indicator to the script engine. It only has any significance over the ‘Return_Ok’ when utilised inside the ‘Action - Rules’ section of an action. If the ‘Rules’ script terminates with the ‘Return_Ok’ statement the main section of the action is executed, however, if the script terminates with the ‘Return_Error’ statement then the remainder of the action is not processed and the current state is returned to the user with the script ‘Report’ forming the error message.

Example;

If (value > 500)
     Report = " – this is a high value pet and cannot be updated"
     Return_Error
EndIf
Return_Ok


Report Statement

The ‘Report’ statement collects string based information to be reported back to the user on completion of the script. The report information will appear in the ‘Message Bar’ at the top of the work region. It is the mechanism through which the developer has the opportunity to report error messages or provide feedback to the end user on the outcome of the script.

Example;

If (value > 500)
	Report = " – this is a high value pet please be careful!"
Else
	Report = " – give the mongrel a quick bath then send him on his way"
EndIf

Output = pet
Return_Ok


Output Statement

The ‘Output’ statement returns information to the user. If the script is called directly; whatever is assigned to the output value of the script will appear in the ‘Work Region’ of the selected ‘View Layout’. If script (A) is called by another script (B), the value of the Output will be returned to script (B) on the completion of script (A).

The following can be assigned to the output:

Custom forms

In this case the form will be rendered in editable form to the user.

Dynamic Groups

The Output command can also be used in conjunction with Groups to create dynamic collections of items. The syntax for this is as follows;

Output = "GROUP [group name]"

where [group name] is the name of a pre-defined group in the application meta-structure. If no more than this is done then on exiting the script a listing page will open containing the Group in question. If, however, an array of items has been entered into the memory cache (see below) with the same name as the Group then the listing page will contain the items inserted into the cache.

Example;

Set arr = Get "Person" Where sql 
Cache Add Key="Important People", Value = arr 
 
Output = "GROUP Important People" 
Return_Ok 

Strings

Strings can be assigned to the Output using either an expression or a string variable. E.g.

Set outputString = "This is a string."
Output = ouptutString

Set name = "Talula-does-the-hula"
Output = "Hello " + name + ", how are you today?"

Items

In this case the underlying item will be returned to the user in edit mode. E.g. Set person = persons[1] Output = person

Arrays

  • If the array contains item variables the the items will be rendered as a list in the work region.
  • If the array contains anything else, then it will be rendered as string in the work region.

Note: In script engine versions before v4.0 the maximum number of items permissible in an array is 10.

To circumvent this limitation ...
If ‘Output’ is assigned a string value of the form
SQL [type name] Where [query expression]
it will be interpreted as a request for list output of the given type subject to the conditional expression provided. The ‘[query expression]’ follows the same rules outlined for the ‘Get’ statement.


Print Statement

The ‘Print’ statement permits a string to be sent to specialised print window. Through this mechanism specialised printable versions of items or forms can be generated. ‘Print’ can be used in conjunction with ‘Output’ and ‘Report’, i.e. a script can include ‘Print’, ‘Output’ and ‘Report’ statements.

Set html = "
" Set html = html + "Stock Items
" Set html = html + "" Set html = html + "" Set html = html + ""

Set items = inv["_items"] For i = 1 To items.Count Set item = items[i]

Set html = html + "" Set html = html + "" Set html = html + ""

Next

Set html = html + "
ProductQuantityItem Price (£)
" + item["Stock Item Name"] + "" + item["Quantity"] + "" + item["Item Price (£)"] + "
"

Print = html Output = inv Report = " – Invoice printed" Return_Ok


Add / To Statement

The ‘Add / To’ statement is used to add elements to an array variable. To use the ‘Add/To’ statement the variable must already have been set up as an array variable using "Set arr = {}" or a similar statement that yields an array type variable.

Example;

Add x To arr

Script Statements Explained

Each statement in ActionScript can exist on a single line and is terminated by a carriage return (i.e. new line or return). The range of allowable statements is fairly limited and they are all summarised below;


// … comment statement used to add developer support to the code

Example;

// a simple comment


Set <var_name> = <expression> Creates and populates a variable with a value

Example;

Set x = 7 + 3
Set person = Do New Object Params Type = “Person”
Set people = Get “Person”
Set person[“First Name”] = “John”


If <expression> / Else / EndIf

Used in combination to allow for the processing of conditionals and executing blocks of statements based on the analysis of conditional statements

Example;

If ( x > 9 )
     Set y = 4
Else
     Set y = 5
EndIf


For < var_name> = var To var / Next

Used in combination to support the basic concept of looping, i.e. executing a block of statements a set number of times

Example;

</tr>
For i = 1 To 5
     Set x = x + i
Next


Do <command> Params <parameters>

used in conjunction with script action definitions to perform more complex operations such as adding attributes to an item or sending emails

Example;

Do Send Email Params From=from, To=to, Subject=”Test Email”, Body=”Nothing”


Return_Ok

used to terminate the execution of the script with the return code ‘OK’

Example;

Return_Ok


Return_Error

used to terminate the execution of the script with the return code ‘Error’

Example;

Return_Error


Report

used to pass information back to the user in the form of a string. The contents of the string will be rendered into the ‘Message Bar’ in the output display

Example;

Report = “ – the script execution completed without error”


Output = <expression>

used to pass items, strings, arrays etc. out of the script and back to the user. The contents of Output will generally be rendered in the work region of the display. Thus, if an item (e.g. a person) is allocated to Output then that item will be returned to the user for editing.

Example;

Output = person


Print = <expression>

used to create a print window containing the string representation of the ‘<expression>’. The string passed to the Print parameter will be rendered in the print window as HTML. The use of HTML provides the developer with the opportunity to format the printable output as desired.

Example;

Print = “<table><tr><td>” + person[“First Name”] + “</td></tr></table>”


Add <var_name> To <arr_name>

used to add a variable to an array type variable

Example;

Add x To array

This completes the list of available statements. There is however one other key construct that is used in conjunction with the ‘Set’ statement that warrants a mention at this stage – the ‘Get’ construct.

‘Get’ is used in conjunction with the ‘Set’ statement to access items in the database. Examples of the syntax for the ‘Get’ statement are;

Set people = Get “Person”
Set johns = Get “Person” Where First Name = “John”
Set sql = “Surname =’Smith’”
Set smiths = Get “Person” Where sql

Note; the use of ‘Get’ will always return an array type variable. Arrays are explained in the next section dealing with the concept of variables in ActionScript.

Each of the statement syntaxes outlined here is described in more detail in the following sections.