Declaring a method
Prefix a function definition with method:
method double(float this) =>
this * 2.0
method magnitude(array<float> this) =>
sumSquares = 0.0
for v in this
sumSquares := sumSquares + v * v
math.sqrt(sumSquares)
- The first parameter is called
thisby convention; its type determines the receiver type. - Everything else works like a user-defined function (default arguments, overloads, nested helpers).
Calling a method
Both forms are equivalent:
x = 5.0
plot(x.double()) // method call
plot(double(x)) // ordinary function call
Methods chain:
prices = array.from(1.0, 2.0, 3.0, 4.0)
m = prices.magnitude() // 5.477…
Built-in methods
Several built-in types expose methods out of the box:
- Arrays:
.push(),.pop(),.get(),.set(),.size(),.sort(),.avg(),.sum(),.stdev(),.first(),.last(),.slice(),.join(), … - Maps:
.put(),.get(),.remove(),.contains(),.size(),.keys(),.values(), … - Matrices:
.get(),.set(),.rows(),.columns(),.add_row(),.add_col(), … - Strings:
.length(),.contains(),.lower(),.upper(),.split(),.replace_all(), … - UDTs: all fields and user-defined methods.
arr = array.from(3.0, 1.0, 2.0)
arr.sort()
log.info(arr.join(",")) // "1,2,3"
Methods on UDTs
Methods on user-defined types pair naturally with the type:
type Pivot
int bar
float price
bool isHigh
method label(Pivot this) =>
this.isHigh ? "H" : "L"
method distanceTo(Pivot this, float px) =>
math.abs(this.price - px)
p = Pivot.new(bar_index, high, true)
log.info(p.label() + " at " + str.tostring(p.price))
log.info("gap: " + str.tostring(p.distanceTo(close)))
Exporting methods
Inside a library() script, a method may be exported just like a regular function:
//@version=1
library("MyMath")
export method square(float this) =>
this * this
Users of the library call it the same way:
import 1000000072/MyMath/1 as mm
y = (3.0).square() + mm.square(4.0)
Exported methods follow the standard library contract (typed parameters, no input.*() inside the body, no reads of input-derived globals).
See also
- User-defined functions
- Objects — types that typically carry methods
- Libraries