Home » Pinescript Syntax » Single-Line Functions in Pine Script

Single-Line Functions in Pine Script

Photo of author
Published on

Introduction to Single-Line Functions

Single-line functions in Pine Script™ offer a concise way to define simple functions. These functions are particularly useful for straightforward calculations or operations that do not require complex logic.

Formal Definition of Single-Line Functions

The structure of a single-line function in Pine Script is as follows:

<function_declaration>
    <identifier>(<parameter_list>) => <return_value>

<parameter_list>
    {<parameter_definition>{, <parameter_definition>}}

<parameter_definition>
    [<identifier> = <default_value>]

<return_value>
    <statement> | <expression> | <tuple>

This structure outlines the function declaration, parameter list, parameter definition, and return value, which can be a statement, expression, or tuple.

Example of a Single-Line Function

Consider the following example of a single-line function:

sumValues(x, y) => x + y

In this example, sumValues is a function that takes two parameters x and y, and returns their sum.

Calling the Function with Different Arguments

Once the function sumValues() is declared, it can be utilized with various types of arguments. Here’s how you can call this function:

resultA = sumValues(open, close)
resultB = sumValues(2, 2)
resultC = sumValues(open, 2)
  • resultA uses open and close as arguments, which are series. Hence, resultA is of type series.
  • resultB is called with two integer literals (2 and 2), making its type integer.
  • resultC combines a series (open) and an integer (2), resulting in a series type.

Understanding the Types

In Pine Script, the type of the variable depends on the types of arguments passed to the function. As seen in the examples:

  • When both arguments are series (like open and close), the function returns a series.
  • When arguments are literal integers, the return type is an integer.
  • A mix of a series and an integer results in a series.

Conclusion and Key Takeaways

  • Single-line functions in Pine Script are succinct and efficient for simple calculations.
  • The type of the return value depends on the argument types.
  • Understanding how to declare and call these functions with different argument types is crucial for effective script writing.

Leave a Comment