Declaring
LIGO functions are the basic building block of contracts.
The semantics of function calls in LIGO is that of a copy of the arguments but also of the environment. This means that any mutation (assignment) on variables outside the scope of the function will be lost when the function returns, just as the mutations inside the functions will be.
Function declarations can be introduced in two main ways: either by
the keyword function
or the keyword const
(the keyword let
is
possible too, but defaulted to const
in this instance). The latter
manner is preferred when the function body is an expression. For
example, here is how you define a basic function that sums two
integers:
This means that add
is a function that takes a pair of integers and
returns their sum.
If the body contains statements instead of a single expression, you
would use a block and a return
statement:
although it is arguably more readable to use function
, like so:
Note that JsLIGO, like JavaScript, requires the return
keyword to
indicate what is being returned. If return
is not used, it will be
the same as return []
(unit).
By default, LIGO will warn about unused arguments inside functions. In
case we do not use an argument, its name should start with _
to
prevent warnings.
Functions can capture variables in their bodies that are defined outside:
We could have the same phenomenon with nested functions instead of two functions at the same scope level: