Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Example for ifelse:

In this example, if tag A equals 1, assign 100 to A. Otherwise, assign 500 to A.

Code Block
languagejs
if (tag.read("A") == 1) {
    tag.write("A", 100.0);
} else {
    tag.write("A", 500);
}

...

The tag "A_WHILE" value will consistently be read and written to the variable val in this example. If the value in the variable val is less than 500, keep incrementing by 1 and store the incremented value to the tag "A_WHILE" in each loop. Once the variable val equals 500, end the loop and exit the script.

Code Block
languagejs
var val = tag.read("A_WHILE");
while (val < 500) {
	val = val + 1;
	tag.write("A_WHILE", val)
	thread.msleep(10)
}

Example for do...while:

The tag "DO_VAL" value will consistently be read and written to the variable do_val in this example. The do loop will increment by 1 and store the value into the tag “DO_VAL” before executing the while loop. Once the variable do_val equals 200, the while loop will terminate, but the do statement will stay executable allowing a user to increment by 1 manually.

Code Block
languagejs
var do_val = tag.read("DO_VAL");
do {
    do_val = do_val + 1;
    tag.write("DO_VAL", do_val)
    thread.msleep(100)
} while (do_val < 200);

Example for for

In this example, the initial expression is 0. When i is less than or equal to 100, i will increment by 1 and store the result in A every execution until i equals 100. Once i equals 100, the for loop will end.

Code Block
languagejs
var i = tag.read("FOR_VAL");
for (i = 0; i <= 100; i = i + 1) {
	tag.write("FOR_VAL", i)
	thread.msleep(100)
}

Example for switchcasebreak

The tag "PET" value will consistently be read and written to the variable pet in this example. The switch will start matching the values between the variable pet and the tag "PET." If the case matches, the expression in the case will execute accordingly. When finished, the break statement will terminate the switch or loop altogether.

Code Block
languagejs
var pet = tag.read("PET")
switch (pet) {
    case "cat":
        tag.write("CASE_STR", "I love cats too!");
        break;
    case "dog":
        tag.write("CASE_STR", "I love dogs too!");
        break;
}

...

In this example, the function keyword calls the values in myFunction to perform multiplication and store the results to the tag "RETURN_ONE." The return statement then outputs the value in the tag "RETURN_ONE."

Code Block
languagejs
function myFunction(a, b) {
	a = a * b;
	tag.write("RETURN_ONE", a);
	return tag.read("RETURN_ONE");
}
var x = myFunction(4, 3);

Example for default

In this example, when the script executes, the tag "REPLY" will be assigned the string value "Hello, my name is CIMON. What is your name?" by default. If the user enters their name, the "NAME" string tag will store their name. If the name entered is "Christian," the "Hi Christian!" will update the "REPLY" string tag.

Code Block
languagejs
var name = tag.read("NAME")
switch (name) {
    case "Christian":
        tag.write("REPLY", "Hi Christian!")
        break;
    default:
        tag.write("REPLY", "Hello, my name is CIMON. What is your name?");
}

...

The tag "TIMER" value will consistently be read and written to the variable timer in this example. When the value in the variable timer is less than 5000 and 10,000, the value in the variable timer will be incremented by 101 each loop until it reaches 5000. When the value in the variable timer reached 5000, the value in the variable timer will be incremented by 1 instead. Once the value in the variable timer reaches 10,000, the while loop will be terminated.

Code Block
languagejs
var timer = tag.read("TIMER");
while (timer < 10000) {
    timer = timer + 1;
    tag.write("TIMER", timer);
    thread.msleep(100)
    if (timer < 5000) {
        timer = timer + 100;
        tag.write("TIMER", timer);
        continue;
        thread.msleep(100)
    }
}

...

In this example, the system.runScript function will call and executes the script name “WHILE_Script.”

...

languagejs

...

The following table is a set of statements and functions for the script.

...

Type

...

Description

...

ifelse Statement

...

The if statement executes the instruction code when the condition is true. Otherwise, the else statement will execute its instruction code. if...else statements can be nested inside another if...else statement using the else if statement which creates a nested loop. Please note, there is no limitation on how many else if can be nested inside if...else statement.

...

while Statement

...

The while statement execution will continue until the expression becomes false.

...

dowhile Statement

...

The do statement is executed at least once before while condition is evaluated. The loop will repeat until while condition becomes false.

...

for Statement

...

A for loop repeats until a specified condition becomes false. Below is the standard syntax used by a for loop:

Code Block
languagejs
for ([initialExpression]; [conditionExpression]; [incrementExpression]) {
    // instruction code
}

...

switchcase Statement

...

Only one default statement can be used in the switch statement. The switch expression is evaluated once by comparing the expression value with the values of each case. If matched, the associated instruction code is executed. Otherwise, default instruction code is executed.

Additionally, case statement must be followed by a constant value and terminated with a colon. Tags, variables, or expressions cannot be used in a case statement.

...

break Statement

...

Terminates a switch or a loop completely. The break statement prevents the execution of the following case in the switch statement. Adding a break function to the last case is good practice. If return is present, break statement is not necessary.

...

function Keyword

...

A block of code designed to perform a particular task and will only executes when something calls it.

...

return Statement

...

Ends function execution and the function caller will return specifies a value.

...

default Statement

...

The default statement is optional and does not need a constant. break statement is not needed either. This statement will execute if no cases get executed.

...

continue Statement

...

The continue statement terminates execution of the current iteration in a loop and then execute the next iteration in a loop. This statement does not terminate the loop completely.

...

system.runScript() Function

...

When an external program is called directly, the caller will be in standby mode until the called program (the external program) ends its operation. However, if an external program is called using runScript(), the caller will not wait until the end of the called program. Both the caller and called program will be executed in parallel.

The following table lists keywords and statements that can be used in a script for better control flow.

Name

Description

ifelse

The if statement executes some specified instructions if the condition is true. Otherwise, the else statement can be used to execute a different set of instructions. else if can be used to specify an alternative condition with different instructions. Once an if or else if statement is executed, any following else if statements will not be executed.

while

A while loop will repeatedly execute until the condition expression becomes false.

dowhile

The do statement allows you to execute the contents of a while loop at least once before the condition is evaluated. If the condition is true, the loop will repeat as usual until the while condition becomes false.

for

A for loop repeats until a specified condition becomes false. Below is the standard syntax used by a for loop:

Code Block
languagejs
for (<initialExpression>; <conditionExpression>; <incrementExpression>) {
    // instruction code
}

A for loop can also be used to iterate over arrays and objects, as explained below.

break

Terminates a switch statement, a while loop, or a for loop completely. The break statement prevents the execution of the following cases in a switch statement. Adding a break statement to each case is good practice.

continue

The continue statement terminates the execution of the current iteration in a loop and then executes the next iteration. Unlike break, this statement does not terminate the loop completely.

switchcase

The switch statement lets you compare an input value to the value of each case. If matched, the instruction code for that case is executed. Otherwise, the default instruction code is executed. Each case statement should usually be followed by a break statement.

default

The default statement specified what should happen if a switch statement does not match any of the cases. A break statement is not required.

function

A function is a block of code designed to perform a particular task. Functions can take in a set of arguments and can return a value. Functions are one of the primary methods for organizing and re-using code.

return

Ends the function execution, and the function will return the specified value to the caller.

arguments

Can be used within a function to get a list of values that were passed into the function call.

Examples for ifelse and else if:

In this example, a notification saying “boolTag is true” will be displayed if the tag’s value is true.

Code Block
if (tag.read("boolTag")) notification.send("boolTag is true.");

You can execute multiple lines of code after an if statement by enclosing the code in curly braces:

Code Block
if (tag.read("boolTag")) {
    notification.send("boolTag is true.");
    thread.sleep(1);
}

In the example below, if tag “A” equals 1, assign 100 to tag “B”. If “A” equals 2, assign 200 to “B”. Otherwise, assign 500 to “B”.

Code Block
languagejs
var value = tag.read("A");
if (value == 1) {
    tag.write("B", 100);
} else if (value == 2) {
    tag.write("B", 200);
} else {
    tag.write("B", 500);
}

Note that the if and else if conditions must be enclosed in parentheses.

Examples forwhile:

The tag "A" will be incremented from 0 to 100 over the course of one second:

Code Block
languagejs
var val = 0;
while (val <= 100) {
	tag.write("A", val);
	val = val + 1;
	thread.msleep(10);
}

Example for dowhile:

The tag “boolTag” will be toggled at least once. If the tag “doLoop” is true after one second, “boolTag” will continue to toggle once per second. Once “doLoop” becomes false, the toggling will stop and the script will end.

Code Block
do {
    tag.write("boolTag", !tag.read("boolTag"));
    thread.sleep(1);
} while (tag.read("doLoop"));

Examples for for

A for loop lets you provide 3 expressions that define the behavior of the loop.

  • The first expression will be run once before the loop first executes. Typically, this is used to initialize a counter variable like i or j.

  • The second expression is a condition that will be checked before each execution of the loop. If the condition is false, the loop will not execute, and the for loop will end. Typically, this is used to check if the counter variable has reached some value.

  • The third expression is run at the end of each execution of the loop. Typically, this is used to increment the counter variable.

In this example, the initial value of i is 0. When i is less than or equal to 100, i will increment by 1 and store the result in the tag “FOR_VAL” every iteration until i equals 100. Once i equals 100, the for loop will end.

Code Block
languagejs
for (var i = 0; i <= 100; i++) {
	tag.write("FOR_VAL", i)
	thread.msleep(100)
}

Looping Over Arrays

A for loop can also be used to iterate through arrays using the array index.

Code Block
// Define an array
var myArray = [
    "val1",
    "val2",
    "val3"
]

// Get the indices
for (var index in myArray) {
	notification.send(index);
} // 0, 1, 2

// Get the values
for (var index in myArray) {
	var value = myArray[index];
    notification.send(value);
} // val1, val2, val3

Looping Over Objects

A for loop can also be used to iterate through objects using keys.

Code Block
// Define an object
var myObject = {
  "key1": "val1",
  "key2": "val2",
  "key3": "val3"
}

// Get the keys
for (var key in myObject) {
    notification.send(key);
} // key1, key2, key3

// Get the values
for (var key in myObject) {
    var value = myObject[key];
    notification.send(value);
} // val1, val2, val3

Example forcontinue

The continue keyword can be used in a while or for loop to move to the next iteration without breaking out of the loop. This can be used to skip specific items.

In this example, a notification will be shown for each number from 0 to 9 except for 5:

Code Block
languagejs
for (var i = 0; i < 10; i++) {
    if (i == 5) {
        continue;
    }
    notification.send(i);
} // 0, 1, 2, 3, 4, 6, 7, 8, 9

Examples for switchcase, break, and default

In this example, when the script executes, the tag "REPLY" will be assigned the string value "Hello, <name>" by default. If the name entered is empty, the “REPLY” tag will be set to "Could not load name." instead.

Code Block
languagejs
var name = tag.read("NAME")
switch (name) {
    case "":
        tag.write("REPLY", "Could not load name.")
        break;
    default:
        tag.write("REPLY", "Hello, " + String(name) + ".");
}

The break statement is used to break out of the switch statement and prevent any other cases from executing. If break is not used, then multiple cases may be executed. This can lead to unexpected behavior, so in most cases, each case should have a break statement.

Examples for function,return, and arguments

This example defines a function called multiply which takes in two arguments a and b, then returns the product a * b. The function is then called in order to set the value of x to the product of 4 and 3.

Code Block
languagejs
function multiply(a, b) {
	return a * b;
}
var x = multiply(4, 3); // x is now equal to 12

Optional Arguments

Functions do not need to have any arguments. For example, here is a function that outputs a message, waits for 3 seconds, then exits the project.

Code Block
function fancyExit() {
    notification.send("Closing the project in 3 seconds...");
    thread.sleep(3);
    system.exit();
}

Function calls are not required to have the same number of arguments as the function definition. Any missing arguments will be set to undefined. This can be used to make certain arguments optional by providing a default value.

In the example below, the function multiplyDefault returns a * b if both a and b are specified. If b is not specified, the function instead returns a * 10.

Code Block
function multiplyDefault(a, b) {
    if (b === undefined) {
        b = 10;
    }
	return a * b;
}
multiplyDefault(2, 3); // 6
multiplyDefault(2); // 20

The arguments keyword

There is also a special keyword arguments, which gives an array containing the values passed into the function call. This allows functions to use a variable number of arguments.

Code Block
function returnFirstArg() {
	return arguments[0];
}
returnFirstExtraArg("a", "b", "c"); // "a"

You can also use arguments in a function definition, in which case arguments will only include values not covered by the named arguments. This is useful when you know that the first few arguments are required, but any additional arguments are optional.

Code Block
function returnFirstExtraArg(x, y, arguments) {
	return arguments[0];
}
returnFirstExtraArg("a", "b", "c"); // "c"

Built-In Functions for Script Importing and Execution

Canvas also provides some built-in functions which allow you to utilize other scripts.

Name

Description

system.importScript

Calls another script in the project directly by name. This pauses the calling script until the target script finishes executing. This can also be used to import functions and variables from other scripts.

system.runScript

When an external program is called directly, the caller will be in standby mode until the called program (the external program) ends its operation. However, if an external program is called using runScript(), the caller will not wait until the end of the called program. Both the caller and called program will be executed in parallel.

Examples forsystem.importScript and system.runScript

Both system.importScript and system.runScript can be used to execute scripts in the project from within another script. The difference is that importScript runs the script in the same thread, and runScript runs the script in a different thread.

Say we have 3 scripts “A”, “B”, and “C”:

Code Block
// A
thread.sleep(1);
notification.send("In A");
Code Block
// B
notification.send("In B");
thread.sleep(1);
notification.send("Stil in B")
Code Block
// C
notification.send("In C");

Running Scripts in Order

We can use system.importScript to execute the scripts in order, like so:

Code Block
system.importScript("A");
system.importScript("B");
system.importScript("C");

The result would be:

  1. sleep for 1 second

  2. display “In A”

  3. display “In B”

  4. sleep for 1 second

  5. display “Still in B”

  6. display “In C”

While the target script is running, the calling script is paused. If there is an error in the target script, the calling script will have an error as well.

Running Scripts Immediately

Scripts can also be run in parallel using system.runScript. This immediately runs the script on another thread.

If we try calling the 3 scripts defined above using runScript

Code Block
system.runScript("A");
system.runScript("B");
system.runScript("C");

The result would be:

  1. display “In B”

  2. display “In C”

  3. sleep for 1 second

  4. display “In A”

  5. display “Still in B”

With runScript, as soon as the target script begins, the calling script resumes execution.

Note that with this method, you cannot guarantee the order of execution. In this case, steps 1 and 2 may be reversed, as well as steps 4 and 5.

Importing Functions and Variables

system.importScript can be used to import functions and variables from other scripts. In this example, we have a script called "myFunctionScript", which returns the Fibonacci sum:

Code Block
// myFunctionScript
function fib(n) {
    if (n <= 0) {
        return 0;
    } else if (n == 1) {
        return 1;
    } else {
        return fib(n - 1) + fib(n - 2);
    }
}
var x = 7;

If we want to use the function fib and the variable x in a different script, we just need to import "myFunctionScript" first:

Code Block
system.importScript("myFunctionScript");
notification.send(fib(x)) // fib(7) -> 13