Script Expressions

Review

An expression is a sequence of arithmetic or string operations specified by the script author, operating with constants, variables and functions from them, including functions with side effects.

The expression is used to substitute as an argument into the value of script components.

The result of the expression can be of type string or number.

Dates are also represented as strings in RFC3339 format.

Values of type bool are automatically converted to the string true or false in the output. Using the ifelse(bool,any,any) function, the result can be converted to other values, for example the numbers 0 or 1.

To use the value of a variable as an argument to an expression, you must specify its name in square brackets, or use the function get_variable_value("VarName") or get_variable_value("VarName",DefaultValue).

To specify a string explicitly, you must enclose the text in quotation marks. Otherwise, all arithmetic combinations available for calculation will be calculated first. In the given examples 2.3 and 2.4, the result will be different in type, but the same in content, that is, the beginning of the resulting line in example 2.3 will be the number 5, and in example 2.4 - the character “5”. Examples 2.5 and 2.6 will give the result "23".

Line splitting is done using the endline() function.

Examples of numeric expressions:

  • (1.1) [variable_number_1] + 1

  • (1.2) 2 ^ [variable_number_2] * ( Log10 ( [variable_number_3] ) + 2 )

  • (1.3) sin ( len ( [variable_string_1] ) )

Examples of string expressions:

  • (2.1) [variable_string_1] + [variable_string_2]

  • (2.2) "Piece of text" + [variable_string_1]

  • (2.3) 2 + 3 + [variable_string_1]

  • (2.4) "2" + "3" + [variable_string_1]

  • (2.5) 2 ++ "3"

  • (2.6) Concat ( 2, "3" )

  • (2.7) SubStr ( [string variable], 1, Length ( [string variable] ) - 1 )

  • (2.8) If ( num([a]) > 5, "more", "less")

Operations

Table 1. Operations on arguments
Function Value type Description

+

num| str

If the arguments can be reduced to numbers, then the result is the sum of the two numbers. Otherwise, the arguments are cast to a string and concatenated.

++

str

Coerces the arguments to a string and concatenates them.

-

num

If the arguments can be reduced to numbers, then the result is their difference. Otherwise, the operation fails with an error.

*

num

If the arguments can be reduced to numbers, then the result is their product. Otherwise, the operation fails with an error.

/

num

If the arguments can be reduced to numbers, then the result is their quotient. Otherwise, the operation fails with an error.

div

int

If the arguments can be reduced to integers, then the result is the integer part of their quotient. Otherwise, the operation fails with an error.

rem

int

If the arguments can be reduced to integers, then the result is the remainder of the division. Otherwise, the operation fails with an error.

==

bool

Converts argument values ​​to the same type and compares them. Equality.

/=

bool

Converts argument values ​​to the same type and compares them. Inequality.

>

bool

Converts argument values ​​to the same type and compares them. More.

>=

bool

Converts argument values ​​to the same type and compares them. Greater than or equal to.

<

bool

Converts argument values ​​to the same type and compares them. Less.

=<

bool

Converts argument values ​​to the same type and compares them. Less than or equal to.

JSON escaping

When working with JSON, collecting a string value requires using string concatenation and escaping double quotes.

Example:
"{
   \"a\": null,
   \"b\": 1,
   \"c\": \"value\",
   \"d\": false,
   \"e\": \"" + str([name]) + "\",
   \"f\": \"" + str(num([a]) + num([res]) + 10) + "\",
   \"g\": [
     \"g1\", \"g2\", \"g3\"
   ],
   \"h\": {
     \"h1\": 1,
     \"h2\": \"value\",
     \"h3\": [1, 2, 3],
     \"h4\": {
       \"h41\": \"" + str(nowtick()) + "\",
       \"h42\": {\"x\": \"value\"}
     }
   }
}"

In some cases, it is more convenient to collect JSON as a template - it is more compact and has fewer escape characters.

At the same time, you can switch from expression to template and back at any time if the current contents of the field are correct.

Templates

The script editor application allows you to define expressions using templates.

A template is a string that contains computable expressions in the form of a macro, delimited by double curly braces {{ …​ }} (see template format).

In this case, the transition between the tabs for specifying a template and specifying an expression produces an automatic mutual conversion.

Below we first describe the old format with single brackets: the templates stored in it are still executed by the server in the same way as previous versions.

Expression Example
"abc." + str([var]) + ".def" + endline() + replace([var],";",".") + substring([var2],3,5) + "zzz"
Template example
abc.{str([var])}.def
{replace([var1],";",".") + substring([var2],3,5)}zzz

In patterns containing curly braces in the values themselves, they should be escaped using a backslash.

Example:
\{
   "a": null,
   "b": 1,
   "c": "value",
   "d": false,
   "e": "{str([name])}",
   "f": "{str(num([a]) + num([res]) + 10)}",
   "g": [
     "g1", "g2", "g3"
   ],
   "h": \{
     "h1": 1,
     "h2": "value",
     "h3": [1, 2, 3],
     "h4": \{
       "h41": "{str(nowtick())}",
       "h42": \{"x": "value"\}
     \}
   \}
\}

Template format

As of version 1.11, the underlying format does not require escaping curly braces; Since version 1.11.7, the script editor saves templates only in it.

A block delimited by double paired curly braces is used as a macro for inserting expressions: {{ …​ }}.

Everything else is text as is: single curly braces, quotes, backslash.

Parts of the template are glued together by a string (1{{ [n] }} with n = 2 gives 12), the macro expression is calculated as a whole.

Two curly braces in a row in the text are written with a backslash: \{\{ and \}\}; }} without backslash - template parsing error.

In the JSON script, such a template is stored in an argument under the key template_v2; key template - for templates of previous versions.

Conversion from expression to template when switching between the corresponding tabs in the script editor also occurs using this format.

Template example
{
  "key1": 1,
  "key2": "{{ [x] }}",
  "key3": {
     "a": "qwerty",
     "b": "{{ [test] }}",
     "c": "{{ md5(now()) }}",
     "d": {{ str(random(1,10) * 10000 + random(10,100)) }}
   },
  "key4": [
     {{ str(hour(now())) }},
     {{ str(minute(now())) }},
     {{ str(second(now())) }}
  ]
}
The corresponding expression
"{
  \"key1\": 1,
  \"key2\": \"" + [x] + "\",
  \"key3\": {
    \"a\": \"qwerty\",
    \"b\": \"" + [test] + "\",
    \"c\": \"" + md5(now()) + "\",
    \"d\": " + str(random(1,10) * 10000 + random(10,100)) + "
  },
  \"key4\": [
    " + str(hour(now())) + ",
    " + str(minute(now())) + ",
    " + str(second(now())) + "
  ]
}"
The corresponding result
{
  "key1": 1,
  "key2": "X-VALUE",
  "key3": {
    "a": "qwerty",
    "b": "TEST-VALUE",
    "c": "D3A09F37ACA99A9258DC261B40286407",
    "d": 70016
  },
  "key4": [
    11,
    15,
    9
  ]
}

Erlang syntax

Expressions are interpreted as erlang code.

Before interpretation, a preliminary translation is performed to support built-in functions and variable substitution.

High-order functions, calls of system modules, as well as plug-in modules added to the system using patches are supported.

Values within single quotes specify atoms (except when single quotes are used in the body of strings, binary expressions, or comments).

Atoms are non-deletable constants until the node is restarted. Therefore, when forming strings, it is better to use double quotes.

When solving a complex algorithmic problem in a script that involves a pure function, it can be useful to translate it into expression code in Erlang.

Below is an example expression in Erlang.

Example
%
io:format("DEBUG. a~n",[]),
    Ctx = jiffy:decode([context],[return_maps]),
io:format("DEBUG. b~n",[]),
    P = jiffy:decode([param],[return_maps]),
io:format("DEBUG. c~n",[]),
%
    Map2 = case P of
         Map when is_map(Map) -> maps:merge(Ctx,Map);
         [<<"merge">>,Map] when is_map(Map) -> r_env_utils:merge_maps(Map,Ctx,2);
         [<<"increment">>,Fld] when is_binary(Fld) ->
            Ctx#{Fld => r_env_utils:to_int(maps:get(Fld,Ctx,0),0) + 1};
         [<<"increment">>,Map] when is_map(Map) ->
            io:format("increment ~120tp~n",[Map]),
            lists:foldl(fun(Fld,Acc) ->
                                Acc#{Fld => r_env_utils:to_int(maps:get(Fld,Acc,0),0) + 1}
                        end, Ctx, maps:keys(Map));
         [<<"append">>,Map] when is_map(Map) ->
             Map1 = r_env_utils:merge_maps(Map,Ctx,2),
             maps:fold(fun(K,V,Acc) ->
                                 case maps:get(K,Ctx,undefined) of
                                       [_|_]=L when is_list(V) -> Acc#{K => L++V};
                                       _ -> Acc
                                 end end, Map1, Map)
    end,
io:format("DEBUG. d~n",[]),
%
    iolist_to_binary(jiffy:encode(Map2, [pretty]))

This particular example implements a context change function in the 'context' variable based on a control command in the 'param' variable.

The format of both values is set by the script itself and maintained in the expression.

The expression uses modules of the erlang platform itself (maps, io), a module of the connected dependency for working with JSON (jsx), a module of the communication platform (r_env_utils), as well as functions of the main erlang module (is_list).

The expression, when executed, outputs debugging information to the node console.

The example uses access to external functions: io:format/2, maps:fold/2, maps:get/3, maps:merge/2, lists:foldl/2, jsx:decode/2, jsx:encode/2, r_env_utils:merge_maps/2, r_env_utils:to_int/1.

Executing external functions through specifying a module requires setting permissions.

This setting is made in the permissions.json file in the 'erlang_apply' section.