Introduction to Multi-Line Functions
Pine Script™ supports multi-line functions for more complex operations that require multiple steps or calculations. These functions are defined over several lines, allowing for intricate logic and variable manipulations.
Syntax of Multi-Line Functions
The basic syntax for a multi-line function in Pine Script is:
<identifier>(<parameter_list>) => <local_block> <identifier>(<list of parameters>) => <variable declaration> ... <variable declaration or expression>
Components of Multi-Line Functions
- Parameter List: Defined similarly to single-line functions, with each parameter optionally having a default value.
- Local Block: The body of the function consisting of multiple statements, each on a separate line.
- Indentation: Each statement within the function body must be indented (using 4 spaces or 1 tab) to denote its inclusion in the function’s scope.
- End of Function Body: The first unindented statement signals the end of the function’s body.
Example: Creating a Geometric Average Function
Consider the function geom_average
which calculates the geometric average of two values:
geom_average(x, y) => squareX = x * x squareY = y * y math.sqrt(squareX + squareY)
In this function:
squareX
andsquareY
are local variables holding the squares ofx
andy
, respectively.- The function
math.sqrt
computes the square root of the sumsquareX + squareY
. - The result of
math.sqrt(squareX + squareY)
is the output of thegeom_average
function.
Understanding the Function’s Flow
- Variable Declaration: The variables
squareX
andsquareY
are declared and calculated within the function. - Final Calculation: The last statement of the function (
math.sqrt(squareX + squareY)
) is the result returned when the function is called. - Indentation: Note the importance of indentation for maintaining the function scope and clarity.
Conclusion and Key Takeaways
- Multi-line functions in Pine Script allow for complex calculations and logical operations.
- Proper indentation is crucial for defining the scope of the function’s body.
- The last statement in the function determines the return value.