---
title: "Expression Evaluator"
app: "Product Configurator"
section: "How-to guides"
last_updated: "2026-09-18"
url: "https://insight-works.com/kb/product-configurator/expression-evaluator/"
---

# Expression Evaluator

Several Insight Works apps provide calculated expression value capabilities, many of which use a common expression evaluator. This evaluator provides calculation capabilities and can also be used with customizations if they include the “Insight Works Rule Builder” library.

For examples using Quality Inspector refer to [https://kb.dmsiworks.com/knowledge-base/quality-inspector-expression-examples/](/kb/quality-inspector/quality-inspector-expression-examples/)

To use the expression evaluator in your own extension, include this dependency in your app.json:

{ "id":  "853c571e-14fe-4798-9b80-437473eeef77", "name":  "Insight Works Rule Builder", "publisher":  "Insight Works", "version": "1.1.0.0" }

Then reference: codeunit 70098512 “IWX Rule Expression Evaluator”.

Standard formula syntax is used, such as (1+2)\*3

## Expression syntax

The Expression Evaluator uses standard mathematical expression syntax. Expressions can contain numbers, variables, mathematical operators, round brackets, and functions.

### Basic arithmetic

The following mathematical operators are supported:

| Operator | Description | Example | Result |
| --- | --- | --- | --- |
| `+` | Addition | `10 + 5` | `15` |
| `-` | Subtraction | `10 - 5` | `5` |
| `*` | Multiplication | `10 * 5` | `50` |
| `/` | Division | `10 / 5` | `2` |

These operators can be combined in a single expression.

For example:

`10 + 5 * 2`

Results in:

`20`

Multiplication and division are evaluated before addition and subtraction.

### Using round brackets

Use round brackets `( )` to group parts of an expression and control the order in which calculations are performed.

For example:

`(10 + 5) * 2`

Results in:

`30`

Without the brackets:

`10 + 5 * 2`

Results in:

`20`

Round brackets can be nested when a calculation contains multiple levels:

`((10 + 5) * 2) / 3`

Results in:

`10`

### Negative numbers

Negative values can be used directly in expressions.

For example:

`-5 + 10`

Results in:

`5`

Negative values can also be passed to functions:

`ABS(-5)`

Results in:

`5`

### Calling functions

Functions are called by entering the function name followed by round brackets.

For example:

`ABS(-10)`

Results in:

`10`

Functions can be used anywhere that a numeric value could otherwise be used.

For example:

`10 + ABS(-5)`

Results in:

`15`

Functions can also be combined with other functions:

`MAX(10; ABS(-20))`

Results in:

`20`

The available built-in functions are listed in the **Formulas** section below.

### Separating function parameters

When a function accepts more than one parameter, separate the parameters with a semicolon (`;`).

For example:

`MAX(10; 20)`

Results in:

`20`

For a function that accepts several values:

`AVG(10; 20; 30; 40)`

Results in:

`25`

Use semicolons rather than commas to separate function parameters.

Each parameter can itself be an expression. For example:

`MAX(10 + 5; 20 * 2; ABS(-30))`

This evaluates the three parameters as:

- `10 + 5` = `15`
- `20 * 2` = `40`
- `ABS(-30)` = `30`

The result is therefore:

`40`

### Nesting functions

Functions can be nested inside other functions.

For example:

`MAX(10; MIN(50; 25))`

The inner expression:

`MIN(50; 25)`

Returns `25`, so the expression becomes:

`MAX(10; 25)`

And returns:

`25`

More complex expressions can combine functions, variables, and normal arithmetic:

`MAX(0; AVG(10; 20; 30) - 5)`

### Functions without parameters

Some functions do not require any parameters. The round brackets are still required.

For example:

`PI()`

returns the value of π.

Similarly:

`E()`

returns Euler’s number.

### Using variables in expressions

Many Insight Works applications make values available to the Expression Evaluator as variables.

For example, if a variable named `Length` has a value of `10`, the following expression:

`[Length] * 1.1`

Results in:

`11`

If the variable has no whitespace, special characters, or mixed case then square brackets are not necessarily needed, however using square-brackets around variables help the parser tell the system “I expect this to be a variable”, particularly when the variable name contains spaces or represents a Business Central field, such as “Item No.”.

For example:

`[Unit Cost] * 1.1`

The variables available depend on the Insight Works application and the context in which the expression is being evaluated. See the **Available Variables** section below for examples.

### Combining variables, functions, and calculations

Expressions are not limited to a single calculation. Variables, mathematical operators, brackets, and functions can all be combined.

For example:

`MAX([Minimum Order Quantity]; ([Average Daily Usage] * 14) + [Safety Stock Quantity])`

This expression:

1. Calculates `[Average Daily Usage] * 14`.
2. Adds `[Safety Stock Quantity]`.
3. Compares that result with `[Minimum Order Quantity]`.
4. Returns whichever value is greater.

Another example:

`ROUND((Length * Width) / 100; 0.01)`

This:

1. Multiplies `Length` by `Width`.
2. Divides the result by `100`.
3. Rounds the final result using the `ROUND` function.

### Handling division by zero

Division by zero normally causes the Expression Evaluator to return an error.

For example:

`10 / 0`

results in a divide-by-zero error.

Use the `IFDIVBY0()` function when an expression may legitimately encounter a zero divisor and you want to return an alternate value instead of an error.

Syntax:

`IFDIVBY0(Expression; ValueIfDivisionByZero)`

For example:

`IFDIVBY0(10 / 2; 0)`

returns:

`5`

Whereas:

`IFDIVBY0(10 / 0; 0)`

returns:

`0`

The first parameter can be a complete expression, including variables, functions, and multiple calculations.

For example:

`IFDIVBY0(([Total Cost] / [Quantity]) * 1.1; 0)`

If `[Quantity]` is zero, the expression returns `0`. Otherwise, it returns the result of the calculation.

Use `IFDIVBY0()` when division by zero is an expected business condition. If division by zero indicates invalid data or an unexpected configuration problem, allowing the normal evaluator error may be preferable because it makes the problem visible.

## Comparison operators and Boolean results

The Expression Evaluator supports comparison operators that compare two numeric values and return a Boolean-style numeric result.

A comparison returns:

- `1` when the comparison is true
- `0` when the comparison is false

The following comparison operators are supported:

| Operator | Description | Example | Result |
| --- | --- | --- | --- |
| `=` | Equal to | `10 = 10` | `1` |
| `<>` | Not equal to | `10 <> 5` | `1` |
| `>` | Greater than | `10 > 5` | `1` |
| `<` | Less than | `10 < 5` | `0` |
| `>=` | Greater than or equal to | `10 >= 10` | `1` |
| `<=` | Less than or equal to | `10 <= 9` | `0` |

Comparisons can be used with variables and calculations.

For example:

`[Quantity] > 100`

returns `1` when `[Quantity]` is greater than `100`, otherwise it returns `0`.

Comparisons can also be used inside functions such as `IF()`.

For example:

`IF([Quantity] > 100; 10; 5)`

returns `10` when `[Quantity]` is greater than `100`, otherwise it returns `5`.

Round brackets can be used to make the intended order of evaluation clear when comparisons are combined with calculations.

For example:

`IF(([Length] + [Width]) > 100; 1; 0)`

This first adds `[Length]` and `[Width]`, then compares the result to `100`.

Because comparison results are numeric, they can also be used directly in other calculations.

For example:

`([Quantity] > 100) * 25`

returns `25` when `[Quantity]` is greater than `100`, and `0` otherwise.

### Boolean values

The Expression Evaluator represents Boolean results numerically rather than using the words `TRUE` and `FALSE`.

In general:

- `1` represents true
- `0` represents false

Functions such as `ANY()` and `ALL()` treat zero as false and non-zero values as true.

For example:

`ANY(0; 0; 5)`

returns `1` because at least one value is non-zero.

`ALL(1; 2; 5)`

returns `1` because all values are non-zero.

`ALL(1; 0; 5)`

returns `0` because one of the values is zero.

Note that `IF()` specifically treats a first parameter greater than or equal to `1` as true. For this reason, comparison expressions that return `1` or `0` are the clearest way to define conditions inside an `IF()` statement.

### Formulas

Several formulas are supported, and developers can add custom formulas to meet specific requirements. The following built-in formulas are supported:

| **Function** | **Description** | **Example** |
| --- | --- | --- |
| ABS(Value) | Calculates the absolute value of the argument. | ABS(-1) ABS(Length-5) |
| ACOS(Value) | Returns the arccosine, or the inverse cosine of a number. | ACOS(1/3)=1.23095941 |
| ACOT(Value) | Returns the angle that is the value of the specified number. | ACOT(3)=0.32175 |
| ALL(Value1; Value2; Value3; Value4; Value5) | Logical operator. Returns 1 if all the values are non-zero. Requires RuleBuilder 1.3 and newer. | ALL(1;0;3.14;[VariableB]) ALL(1;2;3) results in 1. ALL(1;2;3;0) results in 0. |
| ANY(Value1; Value2; Value3; Value4; Value5) | Logical operator. Returns 1 if any of the values are non-zero. Requires RuleBuilder 1.3 and newer. | ANY(1;0;3.14;[VariableB]) ANY(0;0;5) results in 1. ANY(5;0) results in 1. ANY(0;0) results in 0. |
| ASIN(Value) | Returns the angle with the sine that is the specified number. | ASIN(0.3) = 0.30469 |
| ATAN(Value) | Returns the angle with the tangent that is the specified number. | ATAN(0.3) = 0.29146 |
| AVG(Value1; Value2; Value3; Value4; Value5) | Calculates the average of the supplied parameters. Requires RuleBuilder 1.3 and newer. | AVG(9.98; 10.01; 10.00; 9.99; 10.02; 10.03; 9.97; 10.05) results in 10.00625 |
| Ceiling(Value) | The smallest integral value that is greater than or equal to the specified decimal number. | Ceiling(2.01) = 3 |
| Cos(Value) | The cosine of the value. | Cos(Value) |
| Cosh(Value) | The hyperbolic cosine of the value. | Cosh(Value) |
| Cot(Value) | The cotangent of the value, equivalent to cos(value)/sin(value). | Cot(Value) |
| Degrees(Value) | Converts radians to degrees. | – |
| Floor(Value) | The largest integral value less than or equal to the specified decimal number. | Floor(2.9)=2 |
| IEEEREMAINDER(Value1; Value2) | The remainder resulting from the division of Value1 by Value2 using IEEE remainder rules. | – |
| Log(Value1) | The natural logarithm of Value1. | – |
| Log10(Value1) | The base-10 logarithm of Value1. | – |
| Pi() | 3.1415926535897931 | – |
| E() or EULER() | 2.7182818284590451 | – |
| Radians(Value1) | Converts degrees to radians. | – |
| Sign(Value1) | Returns an integer that indicates the sign of Value1. | Sign(-123)=-1 Sign(123)=1 |
| Sin(Value1) | Returns the sine of the value. | – |
| Sinh(Value1) | Returns the hyperbolic sine of the value. | – |
| SQRT(Value1) | Returns the square root of the supplied value. | SQRT(49) = 7 |
| TAN(Value1) | Returns the tangent of the supplied value. | – |
| TanH(Value1) | Returns the hyperbolic tangent of the supplied value. | – |
| TRUNCATE(Value1) or TRUNC(Value1) | Returns the integral part of the supplied value. | Truncate(Pi())=3 |
| Min(Value1; Value2) or Min(Value1; Value2; Value3; …) | Calculates the smallest of the values passed in. RuleBuilder 1.2 and older support two parameters. RuleBuilder 1.3 and newer support up to 100 parameters. | MIN(Var1; 10) MIN(Var1; 10; 100; [VariableB]; 3) |
| Mod(Value1; Value2) | Modulus; provides the integer remainder of a division calculation. The result has the same sign as the divisor. | MOD(3;2) = 1 |
| Max(Value1; Value2) or Max(Value1; Value2; Value3; …) | Calculates the largest of the values passed in. RuleBuilder 1.2 and older support two parameters. RuleBuilder 1.3 and newer support up to 100 parameters. | MAX(Var1; 10) MAX(Var1; 10; 100; [VariableB]; 3) MAX(2;20;5;1) results in 20. MAX(0;-0.00000001;0.00000001;0) results in 0.00000001 |
| POW(Number; Power) | Raises a value to a power. | POW(2;8) |
| Random(OptionalValue1) or Rand(OptionalValue1) | Without a parameter, returns a random number between 0 and 1. If OptionalValue1 is supplied, returns a number between 0 and OptionalValue1. | Random(100) = a number between 0 and 100 Random() = a number between 0 and 1 |
| Randbetween(Value1; Value2) | Similar to Excel’s RANDBETWEEN; returns a value between Value1 and Value2. | RandBetween(100;200) = a value between 100 and 200 |
| Sequence(OptionalValue1) | Provides a simple sequential number that increments. When OptionalValue1 is supplied, the sequence starts at that value in the expression. When it is not supplied, the sequence starts at the last sequence used, or 1. | Sequence() = 1 Sequence() = 2 Sequence() = 3 |
| Round(Value; Precision) | Rounds a value to a certain precision. The precision argument uses Business Central/NAV rounding precision notation; for example, 0.01 means round to two decimal places. | Round(OptionA; 1) |
| RoundUp(Value; Precision) | Similar to Round, but always rounds up instead of to the nearest value. | – |
| RoundDn(Value; Precision) | Similar to Round, but always rounds down instead of to the nearest value. | – |
| IfDivBy0(DivisionFormula; Result) | If DivisionFormula results in a divide-by-zero error, Result is returned instead. If no divide-by-zero error occurs, the division result is returned. | IfDivBy0(1/Length; 0) |
| EQUALS(Value1;Value2) or EQ(Value1;Value2) | If Value1 = Value2, returns 1; otherwise returns 0. | Equals(3.1;3.10)=1 Equals(3.1;3.101)=0 |
| GREATERTHAN(Value1;Value2) or GT(Value1;Value2) | If Value1 > Value2, returns 1; otherwise returns 0. | GT(3.1;3.0)=1 GT(3.1;3.101)=0 |
| LESSTHAN(Value1;Value2) or LT(Value1;Value2) | If Value1 < Value2, returns 1; otherwise returns 0. | LT(3.1;3.101)=1 LT(3.101;3.1)=0 |
| IF(Value1;Value2;Value3) | Similar to Excel’s IF function. If the expression in Value1 is greater than or equal to 1, returns Value2; otherwise returns Value3. | IF(Equals(1;1.01); 2; 3) = 3 IF(Equals(1;1.00); 2; 3) = 2 |
| CustomFunctionName(Value1;Value2) | Custom functions can be added in an extension by subscribing to OnEvaluateCustomFunction in codeunit 70098512 “IWX Rule Expression Evaluator”. | – |
| SUM(Value1; Value2; Value3; Value4; Value5) | An alternative to using +. Useful when dynamic text values supply values to sum and it is unclear how many values might exist. Requires RuleBuilder 1.3 and newer. | SUM(0;1;2;3;4;5;6.6;7.777) results in 29.377 |
| MAD(Value1; Value2; Value3; Value4; Value5) | Median Absolute Deviation (not Mean Absolute Deviation). Measures how consistent a set of inspection readings is while being resistant to outliers. Useful for detecting unstable, noisy, or unreliable measurements. Requires RuleBuilder 1.3 and newer. | MAD(9.98; 10.01; 10.00; 9.99; 10.02; 10.03; 9.97; 10.05) results in 0.02 |
| VARP(Value1; Value2; Value3; Value4; Value5) | Calculates the variance of a population. This can help measure how spread out measurements are from the average. Requires RuleBuilder 1.3 and newer. | VARP(1.00; 1.02; 0.99; 1.01; 0.98) results in 0.0002 |
| RANGE(Value1; Value2; Value3; Value4; Value5) | Calculates the range of the supplied values: the highest measurement minus the lowest measurement. Requires RuleBuilder 1.3 and newer. RANGE() returns 0 with no values | RANGE(10.01; 10.00; 9.98; 10.02) = 10.02 – 9.98 = 0.04 |
| MODE(Value1; Value2; Value3; Value4; Value5) | Calculates the mode of the list using the first value that achieves the highest frequency. Requires RuleBuilder 1.3 and newer. | MODE(1;2;2;3) results in 2. MODE(1;1;2;2;3) results in 1 because it is the first value with the highest frequency. |
| MEDIAN(Value1; Value2; Value3; Value4; Value5) | Calculates the median of the supplied values. Requires RuleBuilder 1.3 and newer. | MEDIAN(10;30;20) = 20 MEDIAN(10;20) = 15 MEDIAN(1;2;3;4) = 2.5 |
| STDDEVS(Value1; Value2; Value3; Value4; Value5) | Calculates sample standard deviation. Use when the supplied values represent a sample rather than the entire population. Requires RuleBuilder 1.3 and newer. STDDEVS() returns 0 with one or fewer values. | STDDEVS(9.98; 10.01; 10.00; 9.99; 10.02; 10.03; 9.97; 10.05) results in 0.0266926956300783 |
| STDDEVP(Value1; Value2; Value3; Value4; Value5) | Calculates population standard deviation. Use when the supplied values represent the entire population. Requires RuleBuilder 1.3 and newer. STDDEVP() returns 0 with no values. | STDDEVP(9.98; 10.01; 10.00; 9.99; 10.02; 10.03; 9.97; 10.05) results in 0.0249687304442977 |
| PERCENTILE(Percentile; Value1; Value2; Value3; Value4; Value5) | Returns the measurement value below which the specified percentage of inspected parts fall. The first parameter is the percentile, from 0 through 100; remaining parameters are the values to use. Requires RuleBuilder 1.3 and newer. | PERCENTILE(90;9.98;10.01;10.00;9.99;10.02;10.03;9.97;10.05;0.90) results in approximately 10.04 |
| CPK(LowerLimit; UpperLimit; Value1; Value2; Value3; Value4; Value5) | Calculates the process capability index. The first parameter is the lower specification limit, the second is the upper specification limit, and the remaining parameters are the values to analyze. Requires RuleBuilder 1.3 and newer. A minimum of 3 parameters must be supplied: lower limit, upper limit, and at least 1 value. CPK() returns 999999 when standard deviation is zero and the mean is inside the specification limits; otherwise 0. | CPK(9.95;10.05;9.98;10.01;10.00;9.99;10.02) results in approximately 1.0541 |

 Note: Arguments in functions are separated by semi-colons. Note: Depending on the use case, there are often existing variables that can be used.

### Available Variables

The following table summarizes the available variables you can use:

| **App** | **Variable** | **Notes** |
| --- | --- | --- |
| Configurator | Any option code can be used within the calculation. | Example: If you have a LENGTH option, you could calculate the amount of child component required using a formula like “Length \* 1.1”. To access parent variables in a subconfiguration, prefix the option name with “PARENT”. For example, “ParentLength \*1.1” |
| Forecast Worksheet | avg\_daily\_usage | Average daily usage of an item. Equivalent to usage\_qty / forecast\_days. Safety stock expressions can often just be set to avg\_daily\_use. |
| Forecast Worksheet | avg\_daily\_forecast | Average daily forecast of an item. This is equivalent to forecast\_qty/forecast\_days You can often use avg\_daily\_forecast to determine the reorder point with: avg\_daily\_forecast \* lead\_time\_days |
| Forecast Worksheet | lead\_time\_days | Lead time of an item. If there is a SKU and it has a “Lead Time Calculation” defined, this is used. If no lead time is available on the SKU, this analyzes the Item, and if the item has a “Lead Time Calculation” defined, that is used. If no lead time is yet available, the Item has a “Vendor No.” supplied, and that vendor had a “Lead Time Calculation” defined, that lead time from that related vendor card is used. |
| Forecast Worksheet | forecast\_qty | This is the forecasted quantity for the period that is supplied by the Sales & Forecast extension. |
| Forecast Worksheet | forecast\_days | Number of forecasted days in the period. |
| Forecast Worksheet | usage\_qty | Usage quantity of an Item for the given period. This considers all negative item ledger entries except for transfers in the period. This Usage Quantity is calculated differently than the Item Planning Review. |
| Item Planning Review | All numeric fields on the item planning buffer table. | All numeric fields on the item planning buffer table can be used, and the notation is to use square brackets to reference them. Examples of available variables that can be used: - [Unit Price] - [Unit Cost] - [Standard Cost] - [Last Direct Cost] - [Indirect Cost %] - [Reorder Point] - [Maximum Inventory] - [Reorder Quantity] - [Discrete Order Quantity] - [Minimum Order Quantity] - [Maximum Order Quantity] - [Safety Stock Quantity] - [Order Multiple] - [Reserved Qty. on Prod. Order] - [Res. Qty. on Prod. Order Comp.] - [Res. Qty. on Req. Line] - [Dampener Quantity] - [Overflow Level] - [Planning Transfer Ship. (Qty).] - [Planning Worksheet (Qty.)] - [Qty. on Purch. Return] - [Qty. on Sales Return] - [Periods] - [Total Quantity] |
| Item Planning Review | lead\_time\_days | Lead time of an item. If there is a SKU and it has a “Lead Time Calculation” defined, this is used. If no lead time is available on the SKU, it analyzes the Item, and if the item has a “Lead Time Calculation” defined, that is used. If no lead time is yet available, the Item has a “Vendor No.” supplied, and that vendor had a “Lead Time Calculation” defined, that lead time from that related vendor card is used. |
| Item Planning Review | Days | This is the number of days between the supplied start and end on the Item Planning Review. |
| Item Planning Review | avg\_daily\_usage | Average daily usage of an item. This is equivalent to usage\_qty / days. Safety stock expressions can often just be set to avg\_daily\_use. |
| Item Planning Review | usage\_qty | Usage quantity of an item for the given period. This considers assembly consumption, assembly output, consumption, negative adjustments, output, and sales by default; you can change this by adjusting the _Item Ledger Filter_ on the _Item Planning Review Setup_ page. This Usage Quantity is calculated differently than the Forecast Worksheet. |
| Quality Inspector | [Item:FieldName] | Provides an ability to do item lookups based on the item that’s on the Quality Inspection Test. [Item:No.] would look up the item number.[Item:Description] would look up the item description. Any field on the item card can be used. The item used is the source item that’s defined on the quality inspection test. If the quality inspection test does not have a source item, this has no effect. Minimum Business Central 18 is required. |
| Quality Inspector | [Attribute:AttributeName] | Provides the ability to do item attribute lookups based on the item that’s on the Quality Inspection Test. [Attribute:Color] would look up the item attribute ‘color’ for the associated item relating to the quality inspection test.[Attribute:Depth] would lookup the depth item attribute from the related item for the test. Any attribute can be used as long as it exists on that item. The item used is the source item defined on the quality inspection test. If the quality inspection test does not have a source item, this has no effect. Minimum Business Central 18 is required. |
| Quality Inspector | [Routing:FieldName] | Intended for use with production related tests. [Routing:No.] would look up the routing no. for the associated routing for the quality inspection test. If the quality inspection test does not have a source item, this has no effect. Minimum Business Central 18 is required. |
| Quality Inspector | [Vendor:FieldName] | Intended for use with receiving related tests that can be connected to a vendor (such as purchase receipts). [Vendor:No.] would look up the vendor no. from the vendor card. If the quality inspection test does not have a vendor, this has no effect. Minimum Business Central 18 is required. |
| Quality Inspector | [Measure:FieldName] | Intended for use with production order-related tests where Business Central quality measures are used. This will allow you to look up a field from the related production order routing quality measure. [Measure:Min. Value] would look up the Min. Value field from the related measure. The measure it looks up would be based on a mapped field or by naming convention for the specific test line that the expression is used on. If the quality inspection test is not related to production or a mapped field, there is no effect. Minimum Business Central 18 is required. |
| Quality Inspector | [Lookup(TableName;FieldName;Field1=Value1,Field2=Value2)] | Provides very simple “first match” single value lookups to other tables in the system. [Lookup(Item;Description;No.=[Source Item No.])] would be functionally equivalent to [Item:Description] Example: You have a table containing thresholds you want to use in your pass condition, but it is based on a choice made in a previous test value, your formula would be similar to this: [Lookup(YourTable;FieldWithValue;KeyField=[ChoiceField])] Minimum Business Central 18 is required. |
| Quality Inspector | [Replace(InputText;SearchFor;ReplaceWith)] | Allows simple text replacements. Example: The expression “[Replace(Cat;C;H)]” would result in “Hat”. Minimum Business Central 18 is required. |
| Quality Inspector | [Classify(InputText;CompareWith;Replacement)] | Allows simple whole-value classification, for example to convert lookups of text values into numerical limits. When the compare text does not match the expression will result in a blank string. When the compare text does match then the expression will result in the replacement text. Example: There is a field called [MyChoice], and it has the possible values of A and B. When the value is A, we want 3, and when the value is B, we want 456. You could use: [Classify([MyChoice];A;3)][Classify([MyChoice];B;456)] Minimum Business Central 18 is required. |
| Quality Inspector | [Copystr(InputText;startPosition;Length)] | Allows simple substring extractions with a 1 based index. Example: You have the text “ABC123DEF” and you wanted “123” from that. [Copystr(ABC123DEF;4;3)] This would begin extracting at the 4th position (where 1 is), and read 3 characters after that. Minimum Business Central 18 is required. |

## Developer extensions

The Expression Evaluator can be extended from another Business Central extension by subscribing to integration events exposed by codeunit **IWX Rule Expression Evaluator**.

This allows developers to add custom functions, provide dynamic variables, modify expressions before they are evaluated, or post-process calculated results without modifying Rule Builder itself.

### Adding a custom function

The recommended event for adding a custom numeric function is:

`OnEvaluateCustomFunctionWithMultipleParams`

This event supports custom functions with zero or more parameters.

For example, the following subscriber adds a custom function named `DOUBLE`:

```
[EventSubscriber(
    ObjectType::Codeunit,
    Codeunit::"IWX Rule Expression Evaluator",
    'OnEvaluateCustomFunctionWithMultipleParams',
    '',
    false,
    false)]
local procedure HandleCustomExpressionFunction(
    ptxtFunctionName: Text;
    var plstOfFunctionParameters: List of [Decimal];
    var pdResult: Decimal;
    var pdicVariableBuffer: Dictionary of [Text, Decimal];
    var pbHandled: Boolean)
begin
    if ptxtFunctionName <> 'DOUBLE' then
        exit;

    if plstOfFunctionParameters.Count() <> 1 then
        Error('DOUBLE requires exactly one parameter.');

    pdResult := plstOfFunctionParameters.Get(1) * 2;
    pbHandled := true;
end;
```

The custom function can then be used anywhere a normal Expression Evaluator function can be used:

`DOUBLE(10)`

returns:

`20`

Because function parameters are parsed as normal expressions, the custom function can also receive calculated values:

`DOUBLE(5 + 5)`

returns:

`20`

Custom functions can accept multiple parameters:

`MYFUNCTION(10; 20; 30)`

or no parameters:

`MYFUNCTION()`

The parameters are supplied to the subscriber in `plstOfFunctionParameters` in the same order in which they appear in the expression.

When the subscriber recognizes and evaluates the function, it must set `pbHandled := true`. If no subscriber handles an unknown function, the Expression Evaluator returns a **Function not defined** error.

### Accessing available variables from a custom function

The `pdicVariableBuffer` parameter contains the numeric variables currently available to the Expression Evaluator.

This allows a custom function to use values from the current evaluation context in addition to its explicit parameters.

For example:

```
if pdicVariableBuffer.ContainsKey('QUANTITY') then
    pdResult := pdicVariableBuffer.Get('QUANTITY');
```

Whenever possible, explicit function parameters are generally easier to understand and maintain. The variable dictionary is useful when a custom function specifically needs access to the evaluator’s current context.

### Adding dynamic variables

Use the `OnBeforeGetDynamicVariable` event when a value needs to be resolved dynamically rather than being added to the evaluator’s variable dictionary in advance.

A subscriber can inspect the requested variable identifier, provide its numeric value, and mark the request as handled.

This is useful when the value must be calculated or retrieved only when the expression actually references it.

### Modifying or replacing an expression before evaluation

The `OnBeforeEvaluateExpression` event is raised before the standard numeric expression evaluation occurs.

A subscriber can:

- Modify the expression before it is evaluated.
- Add or modify values in the numeric variable dictionary.
- Supply the final calculated value itself.
- Set `pbIsHandled := true` to bypass the standard evaluator.

This should generally be used only when the standard functions, variables, and custom-function events are not sufficient.

### Post-processing function results

Use `OnAfterEvaluateFunctionWithMultipleParams` when the result of a function needs additional processing after the function has been evaluated.

The event provides:

- The function name.
- The complete list of numeric parameters.
- The calculated result.
- The available numeric variable dictionary.

Because `pdResult` is passed by reference, a subscriber can modify the final function result.

This event is raised for both built-in and custom functions.

### Customizing numeric values

The `OnBeforeEvaluateNumber` event allows an extension to provide custom conversion of expression text into a numeric value.

This is intended for specialized scenarios where a value that is not normally recognized as a number needs to be interpreted by an extension.

### Extending text-expression processing

The Expression Evaluator also exposes events around text-expression processing and variable replacement.

These include:

- `OnBeforeEvaluateTextExpressionWithVariableBuffer`
- `OnAfterEvaluateTextExpressionWithVariableBuffer`
- `OnBeforeReplaceVariablesInTextExpressionWithVariableBuffer`
- `OnAfterReplaceVariablesInTextExpressionWithVariableBuffer`

These events can be used when an extension needs to modify text expressions or customize how text and numeric variables are substituted before the expression is evaluated.

### Legacy custom-function event

Older versions of Rule Builder exposed:

`OnEvaluateCustomFunction`

This event only provides two individual numeric function parameters.

In current versions, it has been superseded by:

`OnEvaluateCustomFunctionWithMultipleParams`

New development should use `OnEvaluateCustomFunctionWithMultipleParams`, which supports functions with zero to many parameters and avoids the two-parameter limitation of the older event.
