Home » Array Functions » Understanding the map.clear() Function in Pine Script

Understanding the map.clear() Function in Pine Script

Photo of author
Published on

In this article, we’ll dive into the syntax, usage, and an example to illustrate how map.clear() works in practice.

Syntax

The syntax for the map.clear() function is straightforward:

map.clear(id) → void
  • id (any map type): This is the identifier of the map object you wish to clear. The map can be of any type, meaning it can hold integers, floats, strings, booleans, or any other Pine Script data type as keys or values.

Example

Let’s take a closer look at the example provided, with some modifications to the variable names for uniqueness:

//@version=5
indicator("Unique map.clear example")
uniqueOddMap = map.new<int, bool>()
uniqueOddMap.put(1, true)
uniqueOddMap.put(2, false)
uniqueOddMap.put(3, true)
map.clear(uniqueOddMap)
plot(uniqueOddMap.size())
Example

Walkthrough of Code

  1. Indicator Declaration: The script begins with //@version=5 to declare the Pine Script version, followed by indicator("Unique map.clear example") which sets the indicator’s name.
  2. Map Creation: uniqueOddMap = map.new<int, bool>() initializes a new map named uniqueOddMap with integer keys and boolean values.
  3. Adding Key-Value Pairs: The .put() method adds key-value pairs to uniqueOddMap. In this case, three pairs are added, representing whether an integer is odd (true) or even (false).
  4. Clearing the Map: map.clear(uniqueOddMap) clears all key-value pairs from uniqueOddMap, effectively resetting it.
  5. Plotting Map Size: Finally, plot(uniqueOddMap.size()) plots the size of uniqueOddMap. Since the map has been cleared, its size is now 0.

Key Features and Takeaways

  • Function Usability: map.clear() is essential for managing the state of map objects in Pine Script, allowing for dynamic data management within scripts.
  • Syntax and Application: The function requires only the map object’s identifier as an argument, making it simple and straightforward to use.
  • Practical Use Cases: It is particularly useful in scenarios where a map’s data is temporary and needs to be reset for reuse, such as in looping constructs or when re-initializing calculations for different datasets.

By understanding how to use the map.clear() function, you can more effectively manage map objects in your Pine Script indicators or strategies, ensuring clean and efficient data handling.

Leave a Comment