Working with variables in ACLScript

When you write a script in Analytics you often need to account for values that change, or vary. For example:

  • Script configuration You want an easy way of customizing values in a script's logic, such as table or field names, without needing to update every occurrence of a value

  • User input When users run a script, they want to customize input values such as date ranges, or threshold amounts

  • Temporary storage The logic in a script needs to temporarily store a value that is continually updated as the script progresses, such as a counter, or a running total

For these, and other purposes, you use variables.

What is a variable?

You can think of a variable as a named container that holds or stores a value that can change. The value can change, but the name of the variable does not change. As the scriptwriter, you use the fixed variable name throughout the script logic. When the script runs, it does not process the variable name. Rather, it accesses and processes whatever value is currently contained by the variable.

In the example below, v_start_date and v_end_date are variable names, and the dates are the values contained by the variables.

The benefit of variables

Throughout a script you can use variables rather than literal values. By replacing actual table names, field names, text values, numbers, and dates with variables that refer to those items, you greatly increase the flexibility of your script. Instead of writing a script that works for only one very specific situation, you can write a script that can be used in an unlimited number of situations.

How and where can variables be used?

Just like the literal items they refer to, variables can be created, renamed, updated, deleted, used in calculations and a variety of expressions, exported, and extracted. In other words, they can be used in any location where the literal item would be valid.

How do I create a variable?

You create a variable with an Analytics command – the ASSIGN command, or one of several other commands. Typically you include the command in a script, but you can also create a variable manually by entering the ASSIGN command in the Analytics command line.

Example

You want a script to have a customizable date range so you create start date and end date variables.

In the example below, a variable with the name v_start_date currently contains the date value `20210101`, and a variable with the name v_end_date currently contains the date value `20210331`.

You can use these two variables to store whatever start and end dates a user specifies. In the script logic, you specify v_start_date and v_end_date wherever the dates are required, but when the script runs, it uses the actual dates specified by the user.

ASSIGN v_start_date = `20210101`
ASSIGN v_end_date = `20210331`

Tip

You can create one of these variables by copying the ASSIGN command and its parameters to the Analytics command line and pressing Enter. In the Navigator, open the Variables tab to see the result.

If the Command Line text box is not visible, select Window > Command Line.

Displaying variables in an Analytics project

As you work with variables, being able to see the variables that exist in an Analytics project, and their current values, is extremely useful. Two methods let you display variables and their values:

  • the Variables tab

  • the DISPLAY VARIABLES command

The Variables tab

The Variables tab, in the Navigator, tracks the creation of variables and the assignment of values to variables in real time. The read-only tab displays the names, data types, and current values of all variables in an Analytics project. Names are listed alphabetically.

If you step through a script line by line, any variable defined in the script, or any system-generated variable, appears in the Variables tab at the moment of its creation. If the variable already exists, the value updates dynamically, based on the script logic. (In the Script Editor, use the Step option to step through a script.)

Being able to watch exactly what changes are happening with script variables, as they happen, is an important diagnostic tool. This capability allows you to pinpoint script errors that might be hard to locate by examining script syntax alone.

If you run a script, all changes associated with variables are displayed in the Variables tab when a break point is reached, or when the script completes.

The DISPLAY VARIABLES command

The DISPLAY VARIABLES command displays the names, data types, and current values of all variables in an Analytics project. Names are listed in reverse chronological order based on when a variable was created, or most recently updated.

DISPLAY variable_name returns the information associated with a single variable.

You can use the DISPLAY VARIABLES command in two different ways:

  • Current state of project variables Type DISPLAY VARIABLES in the command line and press Enter.

    All variables in the project, and their current values, are displayed in reverse chronological order on screen.

  • State of project variables at different points in a script Add DISPLAY VARIABLES to a script at the point or points in the script where you want to capture the state of project variables. You can also use a break point for this purpose, with the difference that a break point pauses script execution while the DISPLAY VARIABLES command does not.

    After the script completes, double-click the corresponding DISPLAY VARIABLES entry in the command log. The state of project variables at the point in the script that you specified is displayed in reverse chronological order on screen.

Note

You cannot use the DISPLAY VARIABLES command inside a GROUP command.

Eight things to know about ACLScript variables

If you are familiar with other programming or scripting languages then you are already familiar with variables and their many uses. The main characteristics of ACLScript variables are described below.

If you are new to scripting and variables, the information below will make more sense once you start working with variables.

1.  A variable is automatically created when you assign a value

2.  Different methods exist for creating a variable

3.  The data type of a variable is automatically specified

4.  Variable names are flexible, with some restrictions

5.  A variable is global in scope

6.  A variable persists until the Analytics project is closed

7.  A variable can be explicitly deleted

8.  System variables are automatically created by some Analytics commands

1.  A variable is automatically created when you assign a value

A variable is automatically created (declared) when you assign an initial value to the named variable. Assigning an initial value to a variable is also known as initializing a variable.

In the example below, the v_input_table variable is automatically created when you use the ASSIGN command to assign the value "Ap_Trans" to the variable. In other words, creating the variable and assigning a value to the variable (declaring and initializing) occur in a single step.

ASSIGN v_input_table = "Ap_Trans"

When and where should you create a variable?

You can create a variable anywhere in a script as long as creation of the variable precedes first use of the variable.

A best practice is to create all user input variables and script configuration variables at the beginning of a script. If you follow this approach, a user can enter all required input values at the start of a script and then leave the script to run. You can also be confident that all required script configuration variables reside in a single, organized location at the beginning of a script.

Variables that do not need user input or advance configuration can be created at the point in a script where they are required.

If necessary, you can assign a blank value to a character or datetime variable so that the variable exists, but is initially empty.

ASSIGN v_input_table = ""
ASSIGN v_all_field_list = BLANKS(20000)
ASSIGN v_start_date = `19000101`

2.  Different methods exist for creating a variable

How you create a variable depends on how you intend to use the variable.

Usage Creation method

Script configuration

Temporary storage

Other uses in the course of a script

 

ASSIGN command

Use the ASSIGN command on a separate line in a script to declare and initialize a variable. The data type of the assigned value dictates the data type of the variable.

Note

Explicitly specifying the ASSIGN keyword is a best practice because it makes scripts easier to read and understand. However, you can omit the ASSIGN keyword and simply specify:

variable_name = variable_value

User input

ACCEPT command

Use the ACCEPT command to create a basic dialog box that interactively prompts users for one or more script input values. Each input value, regardless of what it represents, is stored in a named character variable.

Also see Creating interactive scripts.

DIALOG command

Use the DIALOG command, and the associated Dialog Builder, to create a more advanced dialog box that interactively prompts users for one or more script input values. Each input value is stored in a named variable. Most of the input options use a character variable.

In addition to the options provided by the ACCEPT command, the DIALOG command gives you additional options such as checkboxes, radio buttons, and dropdown lists.

Also see Creating interactive scripts.

PARAM tag, TABLE tag, FIELD tag

For user input in scripts that run in Robots, create an analytic header and use the PARAM tag, the TABLE tag, or the FIELD tag.

The PARAM tag is the one variable creation method that requires you to explicitly specify a data type for the associated variable.

The TABLE tag and the FIELD tag store input values in a character variable.

Credential input

PASSWORD command

Use the PASSWORD command to create a dialog box that interactively prompts users for a password, a token, or other sensitive information. The PASSWORD command provides secure data entry and encrypted storage of the credential value in a memory location that is protected.

As part of the secure handling of credentials, the variable containing the sensitive information is not displayed and cannot be directly maintained.

Also see Creating interactive scripts.

You can also use the SET PASSWORD command to directly specify a password without requiring user input. However, the password appears in plain text in the script.

PASSWORD tag

For credential input in scripts that run in Robots, create an analytic header and use the PASSWORD tag.

3.  The data type of a variable is automatically specified

When you use the ASSIGN command, the data type of the value assigned to a variable dictates the data type of the variable. This process is known as implicit typing. In most cases, you do not explicitly specify the data type of variables in Analytics.

Tip

Pay close attention to the data types of variables in scripts that you write. A common cause of script errors is a mismatch between the data type of a variable and the way in which you are using the variable. For more information, see The importance of the data type of a variable.

The kinds of values you can assign to a variable

You can assign a literal value to a variable, or you can assign a field to a variable and the variable is initialize with the value of the field in the currently selected record. You can also assign the current value of one variable to another variable.

The data types of values

In Analytics, every data value is one of the following data types (or categories):

  • Character

  • Numeric

  • Datetime

  • Logical

The data type of a value is established in one of the following ways:

  • Literal value The data type of a literal value is established by the presence or absence of qualifiers enclosing the value, and by the alphanumeric characters that make up the value.

  • Field The data type of the values in a field are established by the data type of the field.

  • Variable The data type of the "from" variable and the value it contains is already set and it becomes the data type of the "to" variable. Typically, you do not change the data types of variables once you have created them, although you are not prevented from doing so.

Examples of using the ASSIGN command to create variables of different data types

Note

When you use the ACCEPT command to create a variable, or most of the options in the DIALOG command, the variable has a character data type regardless of the type of value it contains.

Data type of variable and value Example

Character

A character value can include alphanumeric characters and special characters.

A literal character value must be enclosed by single or double quotation marks.

If a character value contains quotation marks, use this approach:

  • If it contains double quotation marks, enclose the entire value with single quotation marks.
  • If it contains single quotation marks, enclose the entire value with double quotation marks.

Character example

Assigns the character value "Vendor_number" to the v_input_table variable.

ASSIGN v_input_table = "Vendor_number"

Assigns the value of the character Vendor_number field in the currently selected record to the v_identifier variable.

ASSIGN v_identifier = Vendor_number

Note

It is important to understand the difference between assigning a qualified and an unqualified field name to a variable.

Assigning "Vendor_number" assigns the actual string of characters that make up the field name.

Assigning Vendor_number assigns one of the values contained in the Vendor_number field.

Numeric

A numeric value can include the numbers 0 to 9, a decimal separator, and a negative sign.

A literal numeric value must not be enclosed by any qualifiers.

Numeric example

Assigns the numeric value 1000 to the v_min_amount variable.

ASSIGN v_min_amount = 1000

Assigns the value of the numeric Invoice_Amount field in the currently selected record to the v_running_total variable.

ASSIGN v_running_total = Invoice_Amount

Datetime

A datetime value can be a date, a time, or a datetime. The value must use a format supported by Analytics.

For more information about supported datetime formats, see Format of datetime literals.

A literal datetime value must be enclosed by backquotes.

Note

Analytics also supports datetime values that use the character data type. For more information, see A word about datetime values.

Datetime example

Assigns the date value `20210101` to the v_start_date variable.

ASSIGN v_start_date = `20210101`

Assigns the value of the datetime Invoice_Date field in the currently selected record to the v_date variable.

ASSIGN v_date = Invoice_Date

Logical

A logical value can be either T or F.

A literal logical value must not be enclosed by any qualifiers.

Logical example

Assigns the logical value T to the v_Q1 variable.

ASSIGN v_Q1 = T

Assigns the value of the logical Approved field in the currently selected record to the v_approved variable.

ASSIGN v_approved = Approved

4.  Variable names are flexible, with some restrictions

For the most part, you can name a variable in whatever way is most suitable for your purpose.

Voluntary conventions

These voluntary conventions make scripts easier to read and understand:

  • Give variables easily understandable, descriptive names that directly relate to the roles the variables perform in a script. A slightly longer, clearly descriptive name is better than a shorter, cryptic name that does not make the purpose of a variable clear.

  • Adopt a general naming convention such as prefacing every variable name with v_ .

Imposed restrictions

Analytics imposes these restrictions on variable names:

  • Maximum length 31 characters

  • Valid characters Alphanumeric characters, and the underscore character ( _ ). The name cannot contain any special characters or spaces, or start with a number.

    Note

    Do not use non-English characters, such as é , in the names of variables that will be used in variable substitution. Variable names that contain non-English characters cause variable substitution to fail.

    Non-English versions of this Help topic, such as the French version, may show variable names with accented characters. Make sure that in an actual script you do not use accented characters in any variable name that will be used in variable substitution.

  • Uniqueness Variable names must be unique within an Analytics project because variables function globally across the entire project

Variable names are not case-sensitive. In ACLScript, v_start_date and v_Start_Date are the same variable.

5.  A variable is global in scope

A variable created in an Analytics script is available to all subsequent parts of the script. It is also available to any other scripts in the Analytics project. This behavior is useful if you want to use a variable in a child script that is defined in a parent script.

ACLScript does not support local scoping of variables.

6.  A variable persists until the Analytics project is closed

A variable remains in your computer's memory until the Analytics project containing it is closed, or until you explicitly delete it.

If you want a variable to persist after you close a project, and be available when you reopen the project, you can create a permanent variable. Preface the variable name with an underscore to create a permanent variable. For example: _v_start_date. Both the variable and the value it contains persist. The only way to get rid of a permanent variable is to explicitly delete it.

Note

Permanent variables are not supported in scripts that run in Robots.

7.  A variable can be explicitly deleted

To explicitly delete one or all variables in an Analytics project, use the DELETE command in the command line or in a script.

To explicitly delete a particular variable:

DELETE variable_name OK

To explicitly delete all variables:

DELETE ALL OK

What gets deleted?

When you delete a variable you are deleting the named container and the value it contains from your computer's memory only.

Deleting a variable does not affect anything related to the variable in a script. You can reinstate the variable in memory by manually running the ASSIGN command in the command line, or by running the script containing the variable assignment.

Deleting a variable and its value also does not affect anything referred to by the value that has an existence outside the variable, such as an Analytics table.

Example

The two examples below illustrate how a variable, and the item referred to by a variable, are separate entities. Deleting one does not affect the other.

Note

The examples use variable substitution to substitute the contents of the variable for the variable name.

In the first example, deleting the variable v_test_table deletes the variable value "Running_totals" but it does not delete the actual Running_totals table.

ASSIGN v_test_table = "Running_totals"

COMMENT Executes successfully
OPEN %v_test_table%

COMMENT Delete the variable
DELETE v_test_table OK

COMMENT Executes successfully
OPEN Running_totals

In the second example, deleting the actual Running_totals table has no effect on the v_test_table variable, although the variable value now refers to a table that does not exist.

ASSIGN v_test_table = "Running_totals"

COMMENT Executes successfully
OPEN %v_test_table%

COMMENT Delete the table referred to by the variable
DELETE FORMAT %v_test_table% OK

COMMENT Fails with the error "Table 'Running_totals' invalid"
OPEN %v_test_table%

8.  System variables are automatically created by some Analytics commands

When you execute certain Analytics commands, system variables are automatically created. For example, the COUNT command generates the COUNTn system variable, which contains the number of records tallied. You can use these variables, and the values they contain, in subsequent portions of a script.

For example, this script automatically terminates if the user selects a table that contains no records:

ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table
OPEN %v_input_table%
COUNT
PAUSE "The table you selected contains no records. The script will terminate." IF COUNT1 = 0
ESCAPE IF COUNT1 = 0
DO SCRIPT summarize_transactions

For more information, see System variables created by Analytics commands.

The importance of the data type of a variable

When an Analytics command or function references a variable, the data type of the variable must match the data type accepted by the command or function. If the data types do not match, you get an error and processing of the command or function fails.

To avoid an error in these situations, you can use Analytics functions to convert the stored value of a variable to a usable data type. For example, this expression converts a date stored in a character variable to a datetime data type:

CTOD(v_character_date)

This expression converts a number stored in a character variable to a numeric data type:

VALUE(v_character_number, 2)

For more information, see Conversion functions.

Note

Dates and numbers are stored in character variables if they are supplied by user input. For more information, see Different methods exist for creating variables.

A word about datetime values

In Analytics, you can process datetime values that use either the datetime data type or the character data type. Typically, the data type associated with datetime values is based on the nature of the data when you import it into Analytics.

What is the implication for variables that contain date, time, or datetime values? Simply put, you need to know the data type of the underlying data that you are working with. Your script syntax needs to differ based on which data type is in use.

Example

The two examples below show the syntax for filtering a date field based on a user-supplied date range.

  • In the first example, the date field uses a datetime data type.

  • In the second example, the date field uses a character data type.

  • In both examples, the v_start_date and v_end_date variables use the character data type because they were created using either the ACCEPT command or the DIALOG command.

In the first example, you must use the CTOD( ) function to convert the date range values from the character data type to the datetime data type. (CTOD stands for "Character to Date".) You must perform this conversion so that the data type of the date range values matches the data type of the datetime date field.

SET FILTER TO BETWEEN(datetime_date_field, CTOD(v_start_date), CTOD(v_end_date))

In the second example, you do not perform any conversion of the date range values because they already match the data type of the character date field. If you convert them, they no longer match and you get a script error.

SET FILTER TO BETWEEN(character_date_field, v_start_date, v_end_date)

Variable substitution

When you use a character variable as input for an Analytics command or function you need to substitute the value of the variable for the variable name. If you do not perform this substitution, the command or function attempts to operate on the actual variable name, rather than the value contained by the variable, and an error results.

Variable substitution is the method for substituting the value contained in a character variable for the variable name. To use variable substitution, you enclose the name of the character variable in percentage signs ( % ). For example, %v_input_table% retrieves the actual table name stored in v_input_table and substitutes it for the variable name.

Because user input for a script is most often stored in a character variable, a common use for variable substitution is when incorporating user input into script logic.

Note

Variable substitution is only intended for use with character variables that contain values that represent character data. An unreliable result or an error can occur if you use variable substitution with variables of other data types, or with character variables that contain values that represents a number, a datetime, or a logical value.

Example

You want a script to allow a user to select an input table. The script then opens the table selected by the user. You use variable substitution with the OPEN command so that the command acts upon the correct table name.

When you specify OPEN %v_input_table% , what the script actually sees is:

OPEN Name_of_table_selected_by_user

ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table
OPEN %v_input_table%

If you do not use variable substitution in this example, the script will most likely fail because the OPEN command is trying to open a table called v_input_table , and no table with that name exists.

ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table
OPEN v_input_table

Using variable substitution can be tricky

Certain situations may look like they call for variable substitution, but in fact variable substitution causes an error.

Consider one of the examples previously presented:

SET FILTER TO BETWEEN(character_date_field, v_start_date, v_end_date)

In this example, you are comparing date values stored as character data in both the variables and the field, so using variable substitution with the variables should work:

SET FILTER TO BETWEEN(character_date_field, %v_start_date%, %v_end_date%)

So why does variable substitution cause an error in this situation? The answer is that variable substitution is absolutely literal. To troubleshoot the error, look at the precise values stored in the variables, manually substitute them into the expression, and look at the resulting expression. For example:

SET FILTER TO BETWEEN(character_date_field, 20000101, 20001231)

This expression compares dates that use a character data type with numbers that post-substitution use a numeric data type, which is a mismatch of data types.

Because you specified a character field with BETWEEN( ), the function automatically interprets the values in v_start_date and v_end_date as character values and there is no need to use variable substitution.

For more information, see Troubleshooting.

An exception to the rule

In some instances, you may be able to use variable substitution with a numeric variable without issue. The benefit is that the value of the numeric variable is captured in the log, which can be helpful for troubleshooting.

Both of the examples below assign the value of the COUNT1 numeric variable to the v_counter numeric variable. However, in the first example, the actual assigned value is not captured in the log. In the second example, the actual value is captured.

COMMENT log entry: ASSIGN v_counter = COUNT1
ASSIGN v_counter = COUNT1
COMMENT log entry: ASSIGN v_counter = 500
ASSIGN v_counter = %COUNT1%

Manually maintaining variables

You can manually maintain variables using the Variables dialog box, available from the Analytics main menu. You can create, rename, duplicate, or delete variables, or update variable values.

Any maintenance you perform affects the current instance of the variable in memory only. For example, if you rename a variable, you are renaming only the instance of the variable in memory. You are not renaming the variable in a script.

Note

The ability to manually maintain variables through the user interface may be convenient in some instances. Manual maintenance does not offer any additional functionality versus maintaining variables using commands.

Most script writers work with variables exclusively in the Script Editor and associated features such as the command line and the Variables tab.

  1. From the Analytics main menu, select Edit > Variables.

    The Variables dialog box opens and displays a list of all system and user-defined variables in the project. System variables are those created automatically by commands.

  2. Do any of the following:
    Create a new variable
    1. Click New to open the Expression Builder.

    2. In the Expression text box, enter the value or the expression to assign to the variable.

      Literal values must use the correct format and qualifiers (when required). For more information, see The data type of a variable is automatically specified.

    3. Optional. Click Verify to check that the value or expression is valid.

    4. Type the variable name in the Save As text box.

      For more information, see:

    5. Click OK.

      The variable is created and appears in the Variables tab.

    Update a variable value
    1. Select a variable in the list and click OK to open the Expression Builder.

    2. In the Expression text box, update the value or the expression assigned to the variable.

      Literal values must use the correct format and qualifiers (when required). For more information, see The data type of a variable is automatically specified.

    3. Optional. Click Verify to check that the value or expression is valid.

    4. Click OK.

      The value assigned to the variable is updated in your computer's memory.

    Rename a variable
    1. Select a variable in the list and click Rename.

    2. In the Rename text box, enter a new name and click OK.

      The variable is renamed in your computer's memory.

    3. Click Cancel to close the Variables dialog box.

    Duplicate a variable
    1. Select a variable in the list and click Duplicate.

      The variable and its value are duplicated in your computer's memory. A numeric suffix is added to the name of the duplicated variable.

    2. Do one of the following:

      • Click Done to close the Variables dialog box.

      • Click OK to update the value or expression assigned to the variable.

    Delete a variable
    1. Select a variable in the list.

    2. Optional. Shift+click or Ctrl+click to select multiple variables for deletion.

    3. Click Delete.

    4. Click Delete again.

      The variable or variables are deleted from your computer's memory.

    5. Click Done to close the Variables dialog box.

Examples of variable use

Variables for script configuration

You want to create a script that calculates sales tax amounts, with the ability to handle sales tax rates that periodically change.

Required variables

To allow configuration of different tax rates and a date range, you use the ASSIGN command to create the following set of variables.

Variable name Variable contains
v_tax_1 The first tax rate
v_tax_2 The second tax rate
v_tax_2_start The date that the second tax rate goes into effect
v_tax_2_end The date that the second tax rate ends, or the current date if the tax rate is still in effect.

The script

COMMENT Create and initialize variables for sales tax rates and a date range
COMMENT If required, you can extend the script by adding additional tax rate and date range variables
ASSIGN v_tax_1 = 0.05
ASSIGN v_tax_2 = 0.06
ASSIGN v_tax_2_start = `20210701`
ASSIGN v_tax_2_end = `20211231`

COMMENT Create a conditional computed field that uses different sales tax rates for two different periods
DEFINE FIELD sales_tax COMPUTED

Invoice_Amount * v_tax_2 IF BETWEEN(Invoice_Date, v_tax_2_start, v_tax_2_end)
Invoice_Amount * v_tax_1

The created and initialized variables in the Variables tab

After you run the script, the created and initialized variables are displayed in the Variables tab.

Because the ASSIGN command creates the variables, the data type of the assigned values dictates the data type of the variables. In this example, there are two numeric variables and two datetime variables.

Variables for user input

You want to create a script that allows a user to select any table in an Analytics project, filter the records in the table by a numeric range and a date range, and output the filtered records to a new table.

Required variables

To capture the user input for the script, you use the ACCEPT command to create the following set of variables.

Variable name Variable contains
v_input_table The name of the Analytics table to use as input
v_output_table The name of the Analytics output table for the filtered records
v_numeric_field The numeric field in the input table to use with the numeric range
v_min_amount The bottom end of the numeric range
v_max_amount The top end of the numeric range
v_date_field The date field in the input table to use with the date range
v_start_date The earliest date in the date range
v_end_date The most recent date in the date range

Scripting considerations

Because you use the ACCEPT command to interactively prompt users for script input values, each input value is stored in a named character variable even if the value represents a number or a date. To account for this fact, you need to use Analytics functions at certain points in the script to convert the variable value to the data type required by the script logic.

For example:

  • The VALUE( ) function converts the number stored in v_min_amount from a character data type to a numeric data type:

    VALUE(v_min_amount, 2)
  • The CTOD( ) function converts the date stored in v_start_date from a character data type to a datetime data type:

    CTOD(v_start_date)

You need to make these data type conversions because the values in these variables are being compared against values in fields that use a numeric or datetime data type.

You also need to use variable substitution to access the actual names of the tables and the fields stored in some of the variables.

For example:

OPEN %v_input_table%

The script

COMMENT Create a dialog box to prompt the user for an input table and an output table
ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table, "Specify an output table name (no spaces):" TO v_output_table

COMMENT Open the input table selected by the user
OPEN %v_input_table%

COMMENT Create a dialog box to prompt the user for a numeric field and a numeric range
ACCEPT "Select a numeric field to filter by:" FIELDS "N" TO v_numeric_field, "Specify a minumum amount:" TO v_min_amount, "Specify a maximum amount:" TO v_max_amount

COMMENT Create a dialog box to prompt the user for a date field and a date range
ACCEPT "Select a date field to filter by:" FIELDS "D" TO v_date_field, "Specify a start date (YYYYMMDD):" TO v_start_date, "Specify an end date (YYYYMMDD):" TO v_end_date

COMMENT Filter the input table based on the user's numeric and date ranges
SET FILTER TO BETWEEN(%v_numeric_field%, VALUE(v_min_amount, 2), VALUE(v_max_amount, 2)) AND BETWEEN(%v_date_field%, CTOD(v_start_date), CTOD(v_end_date))

COMMENT Extract the filtered set of records to the output table specified by the user
EXTRACT RECORD TO %v_output_table%

COMMENT Open the output table with the filtered records
OPEN %v_output_table%

The created and initialized variables in the Variables tab

After you run the script, the created and initialized variables are displayed in the Variables tab.

Because the ACCEPT command creates the variables, the variables use the character data type even if the variable value represents a number or a date.

WRITE1 is a system variable. In this current situation, the value represents the number of records in the output table ( v_output_table ). For more information, see System variables created by Analytics commands.

Default values for user input variables

You can prefill a default value into a user input field instead of presenting a blank field to the user. A default value can save effort and also reduce errors by displaying the correct format for an input value.

To specify a default value you first use the ASSIGN command to initialize a variable with the default value. You then use the ACCEPT command with the same variable name to allow the user to optionally overwrite the default value.

This example is the same as Variables for user input above, with the addition of a preliminary section to initialize variables with default values for the numeric and date ranges.

Initializing variables with default values

To initialize variables with default values, you use the ASSIGN command to create the following variables.

Variable name Variable contains
v_min_amount The bottom end of the numeric range
v_max_amount The top end of the numeric range
v_number_of_months The length of the date range in months
v_end_date The most recent date in the date range (calculated)
v_start_date The earliest date in the date range (calculated)

Scripting considerations

Because you are prefilling default values into fields created by the ACCEPT command, those values must use the character data type. If you attempt to prefill values of another data type, the values do not appear.

To account for this fact, you may need to use Analytics functions to convert the default values to the character data type. (Later in the script, you can use other functions to covert the variable values back to the data type required by the script logic.)

For example:

  • The STRING( ) function converts the number 5000 to a character string that is then stored in the v_min_amount variable:

    ASSIGN v_min_amount = STRING(5000, 4)
  • The DATE( ) function converts the calculated end date to a character string that is then stored in the v_end_date variable:

    ASSIGN v_end_date = ALLTRIM(DATE(EOMONTH(TODAY(),-1)))

Date range calculation

The date range calculation sets the default range to the 12 complete months prior to the current date. To change the length of the range, update the value assigned to the v_number_of_months variable. To learn more about the function used to calculate the date range, see EOMONTH( ) function.

The script

COMMENT Set the date format for the duration of the Analytics session
SET DATE "YYYYMMDD"

COMMENT Specify default values for the bottom and top ends of the numeric range
ASSIGN v_min_amount = STRING(5000, 4)
ASSIGN v_max_amount = STRING(100000, 6)

COMMENT Specify the length of the calculated date range in months
ASSIGN v_number_of_months = 12

COMMENT Calculate the start and end dates of the default date range based on the current date and the length specified by v_number_of_months
ASSIGN v_end_date = ALLTRIM(DATE(EOMONTH(TODAY(),-1)))
ASSIGN v_start_date = ALLTRIM(DATE(EOMONTH(CTOD(v_end_date), -v_number_of_months) + 1))

COMMENT Create a dialog box to prompt the user for an input table and an output table
ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table, "Specify an output table name (no spaces):" TO v_output_table

COMMENT Open the input table selected by the user
OPEN %v_input_table%

COMMENT Create a dialog box to prompt the user for a numeric field and a numeric range
ACCEPT "Select a numeric field to filter by:" FIELDS "N" TO v_numeric_field, "Specify a minumum amount:" TO v_min_amount, "Specify a maximum amount:" TO v_max_amount

COMMENT Create a dialog box to prompt the user for a date field and a date range
ACCEPT "Select a date field to filter by:" FIELDS "D" TO v_date_field, "Specify a start date (YYYYMMDD):" TO v_start_date, "Specify an end date (YYYYMMDD):" TO v_end_date

COMMENT Filter the input table based on the user's numeric and date ranges
SET FILTER TO BETWEEN(%v_numeric_field%, VALUE(v_min_amount, 2), VALUE(v_max_amount, 2)) AND BETWEEN(%v_date_field%, CTOD(v_start_date), CTOD(v_end_date))

COMMENT Extract the filtered set of records to the output table specified by the user
EXTRACT RECORD TO %v_output_table%

COMMENT Open the output table with the filtered records
OPEN %v_output_table%

Variables for temporary storage

You want to create a script that calculates a running total based on values in a numeric field. The running total starts at zero (0.00) for each unique value in an identifier field.

Required variables

The script uses variables for three different purposes:

  • user input

  • temporary storage of values

  • script configuration

User input

To capture the user input for the script, you use the ACCEPT command to create the following set of variables.

Variable name Variable contains
v_input_table The name of the Analytics table to use as input
v_output_table The name of the Analytics output table for the running totals
v_id_field The field in the input table containing identifier values such as customer or vendor IDs
v_numeric_field The numeric field in the input table to use for calculating running totals
Temporary storage of values, and script configuration

To allow the temporary storage of values as the script processes the input table record by record, you use the ASSIGN command to create, and also update, the following two variables. If required, you can configure a start point for the running total other than zero (0.00).

Variable name Variable contains
v_id_value The identifier value in the record that the script is currently processing
v_running_total

The running total value in the record that the script is currently processing

The script

COMMENT
Allow overwriting of files without displaying a confirmation dialog box
END
SET SAFETY OFF

COMMENT
Create a dialog box to prompt the user for an input table and an output table
END
ACCEPT "Select an input table:" FIELDS "xf" TO v_input_table, "Specify an output table name (no spaces):" TO v_output_table
OPEN %v_input_table%

COMMENT
Create a dialog box to prompt the user for a character identifier field
END
ACCEPT "Select a character identifier field:" FIELDS "C" TO v_id_field

COMMENT
Create a dialog box to prompt the user for a numeric field
END
ACCEPT "Select a numeric field:" FIELDS "N" TO v_numeric_field

COMMENT
Index (sort) the table on the character identifier field
END
INDEX ON %v_id_field% TO "ID_field_sorted"
SET INDEX TO "ID_field_sorted"

COMMENT
Assign the current value in the character identifier field to the v_id_value variable.
When v_input_table is first opened, the current value is the first value in the field. Subsequently, the current value depends on the record currently being processed by the script.
END
ASSIGN v_id_value = %v_id_field%

COMMENT
Set the start value for the running total to zero (0.00)
END
ASSIGN v_running_total = 0.00

COMMENT
Process the table record by record. For each unique identifier, calculate a running total for the numeric field.
END
GROUP IF v_id_value = %v_id_field%
  ASSIGN v_running_total = v_running_total + %v_numeric_field%
  EXTRACT %v_id_field% %v_numeric_field% v_running_total AS "%v_numeric_field% running total" TO %v_output_table%
ELSE
  ASSIGN v_id_value = %v_id_field%
  ASSIGN v_running_total = 0.00
  ASSIGN v_running_total = v_running_total + %v_numeric_field%
  EXTRACT %v_id_field% %v_numeric_field% v_running_total AS "%v_numeric_field% running total" TO %v_output_table%
END

COMMENT Open the output table with the calculated running totals
OPEN %v_output_table%

COMMENT Restore the default behavior of displaying a confirmation dialog box before overwriting files
SET SAFETY ON

The created and initialized variables in the Variables tab

After you run the script, the created and initialized variables are displayed in the Variables tab.

The variables created by the ACCEPT command use the character data type. The variables created by the ASSIGN command ( v_id_value , v_running_total ) use the data type of the assigned value.

The values assigned to v_id_value and v_running_total are continually updated as the script progress. The Variables tab displays their final values before the script completes.

For information about the system variables ( WRITEn ) and their numbering scheme, see Incrementally numbered system variables.

Troubleshooting

Two general categories of error are the most common when working with variables in scripts:

  • Unexpected results The script runs to completion but analysis that includes variables does not produce the expected results.

  • Data type issue The script fails with an error related to data type such as "Expression type mismatch" or "Character expression is required".

Unexpected results

For the first kind of error, try this troubleshooting approach:

  1. In the Navigator, open the Variables tab.

  2. In the Analytics command line enter DELETE ALL OK to delete any existing variables.

    If the Command Line text box is not visible, select Window > Command Line.

  3. In the Script Editor, use the Step option to step through the script line by line and track the creation of each variable and assigned value in the Variables tab.

    You may discover that the value being assigned to a variable is not what you intended and your script logic needs to be adjusted. For more information, see Testing and debugging scripts.

Note

You cannot step through the content of multiline commands such as GROUP, LOOP, or DEFINE FIELD . . . COMPUTED. To test script logic in this situation, temporarily copy the script logic without the surrounding command syntax into a separate script.

Data type issue

As you develop scripts that make use of variables you will likely encounter errors caused by mismatched data types. Errors are especially likely if you are combining conversion functions and variable substitution in the same expression.

Encountering errors is normal, and the way to overcome them is to test different approaches and to keep these principles in mind:

  • Pay very close attention to the data types in every element in an expression. Are all the data types in an expression aligned in the way that ACLScript requires?

  • Remember that variable substitution is absolutely literal. If you suspect that variable substitution is causing an error, look at the precise value stored in a variable and manually substitute the value into the expression. Just performing this simple troubleshooting step may reveal the problem.

  • Inserting the DISPLAY VARIABLES command at different locations in a script allows you to capture the point-in-time state of project variables.

  • Stepping through a script line by line, and setting break points, can make troubleshooting much easier. For more information, see Testing and debugging scripts.