exprv4:tutorials:functions_and_methods



Functions and Methods

Functions and methods let you reuse behavior.

A function is called by name:

print('Hello');
sqrt(25);

A method is called on a value or object:

'hello'.upper();
(255).to_hex();

The difference is the call style:

  • Function: `name(arguments)`
  • Method: `value.name(arguments)`

Built-In Functions

Expr includes built-in functions that are available without defining them yourself.

print('Hello from Expr');
sqrt(25);
sin(pi() / 2);
max(10, 20);

Some functions are used for output:

print('Probing started');

Some functions calculate values:

radius = sqrt(25);
angle = deg2rad(90);
value = sin(angle);

Type checks and conversions are not global functions. They are value methods and are introduced below.

Built-in functions are documented in the reference manual. This tutorial only introduces the call style.


Arguments

Values passed to a function are called arguments.

max(10, 20);

Here, `10` and `20` are arguments.

Arguments can be calculations:

max(10 + 5, 20 * 2);

Arguments can also be variables:

a = 10;
b = 20;
max(a, b);

Functions check how many arguments they expect. Calling a function with the wrong number of arguments is an error.


Return Values

Many functions produce a value.

r = sqrt(25);
r;

The final value is `5`.

A function call can be used inside a larger expression:

diameter = 10;
area = pi() * (diameter / 2) ** 2;
area;

Some functions are used mainly for their action. For example, `print()` writes output.

print('Tool change started');

Methods

Methods are called with a dot after a value or object.

value.methodName(arguments);

Strings have string methods:

name = ' tool 1 ';
cleanName = name.trim().upper();
cleanName;

The final value is `'TOOL 1'`.

Numbers have number methods:

value = 255;
hexText = value.to_hex();
hexText;

Methods can be chained when each method returns a value that has another method.

'  probe ready  '.trim().upper();

The final value is `'PROBE READY'`.


Common String Methods

String methods are useful for messages, dialog values, file names, table text, and parsed data.

'Probe'.length();              // 5
'Probe ready'.contains('ready');
'Probe ready'.substr(0, 5);    // 'Probe'
'  text  '.trim();             // 'text'
'abc'.upper();                 // 'ABC'
'ABC'.lower();                 // 'abc'
'Tool 1'.startswith('Tool');
'Tool 1'.endswith('1');
'Tool 1'.indexof(' ');         // 4

Some string methods convert text into other values:

'123'.parse_num();
'FF'.parse_hex();
'true'.parse_bool();

Common Number Methods

Number methods are useful for checks, conversions, and formatted output.

(42).is_num();
(42).is_num_int();
nan().is_nan();
(255).to_string();
(255).to_hex();
(5).bit(0);

Parentheses are useful when calling a method on a numeric literal:

(255).to_hex();

Without parentheses, the parser can be harder to read, especially around decimal numbers.


Object Methods

Some built-in functions create objects. Objects usually have methods.

For example, arrays and maps use method calls:

items = array();
items.add('A');
items.add('B');
items.to_string();

Maps also use methods:

settings = map();
settings.set('speed', 1200);
settings.set('tool', 'T1');
settings.to_string();

Different object types provide different methods. Use the reference manual for the full list.


Defining Your Own Function

Use `function` to define reusable logic.

function ToolRadius(diameter)
{
    return diameter / 2;
}
 
ToolRadius(6);

The final value is `3`.

A function definition has:

  • The `function` keyword.
  • A function name.
  • Parameter names inside parentheses.
  • A block of code.
function Name(parameter1, parameter2)
{
    // function body
}

Function Parameters

Parameters are local names used inside the function.

function Clamp(value, low, high)
{
    if(value < low)
    {
        return low;
    };
 
    if(value > high)
    {
        return high;
    };
 
    return value;
}
 
Clamp(120, 0, 100);

The final value is `100`.

When the function is called, the argument values are assigned to the parameter names.


Return

Use `return` to leave a function and produce a result.

function IsProbeErrorLarge(error)
{
    if(error > 0.10)
    {
        return true;
    };
 
    return false;
}
 
IsProbeErrorLarge(0.12);

The final value is `true`.

A function can also produce the value of its last expression, but explicit `return` is clearer for beginner scripts and for workflow logic.

function Add(a, b)
{
    a + b;
}
 
Add(2, 3);

The final value is `5`.

For important scripts, prefer this style:

function Add(a, b)
{
    return a + b;
}

When To Create a Function

Create a function when:

  • The same calculation is used more than once.
  • A script becomes hard to read.
  • You want to give a name to a step in a workflow.
  • You want to separate probing, ATC, dialog, or validation logic into smaller pieces.

Example:

function ProbeStatus(error)
{
    if(error <= 0.01)
    {
        return 'excellent';
    }
    else if(error <= 0.05)
    {
        return 'acceptable';
    }
    else if(error <= 0.10)
    {
        return 'warning';
    };
 
    return 'failed';
}
 
ProbeStatus(0.03);

The final value is `'acceptable'`.


Functions vs Methods

Use this rule of thumb:

  • Use a function when the operation stands alone: `sqrt(25)`, `print('text')`, `ToolRadius(6)`.
  • Use a method when the operation belongs to a value or object: `'text'.upper()`, `(255).to_hex()`, `items.add('A')`.

The syntax tells you what is being used:

print('Hello');      // function
'Hello'.upper();     // method

Scope Comes Next

Functions introduce local names, parameters, return values, and temporary helper variables. The next chapter explains scope rules and the set keyword.

Classes come after scope, because object methods also use the same name lookup and local-variable rules.


Common Mistakes

Missing Parentheses

Function and method calls need parentheses.

print('Hello');
'hello'.upper();

Wrong Number of Arguments

This is an error if the function expects two arguments:

max(10);

Calling a Method on the Wrong Type

String methods belong to strings.

'hello'.upper();

Do not call a string method on a number unless that method exists for numbers.

Forgetting return

A function can return the last expression, but explicit `return` is usually clearer.


Try This

Read this script and predict the final value:

function FormatToolName(toolNumber)
{
    return ('tool ' + toolNumber).upper();
}
 
FormatToolName(3);

The final value is `'TOOL 3'`.

Next: Scope and set

exprv4/tutorials/functions_and_methods.txt · Last modified: by 127.0.0.1

Page Tools