This is a follow-up to my previous question Plotting custom data - daily = ok, weekly = not ok.
The comments on the accepted answer suggests that the state of a var
inside a function is persisted throughout successive calls to that function.
This proved to be correct, because removing the var
solved my problem.
However, I now have a test case that seems to prove the opposite.
In the script below, variable b
seems NOT to be persisted.
Function f2()
has to be called on every bar in order to evaluate the if
statement.
That is the case, since the plot of y
is equal to the number of bars.
Because function f2()
also calls f1()
, I expect variable b
inside of f1()
to also increase by 1 on each bar.
The final value of b
inside of f1()
is retrieved on the last bar, and stored in z
.
To my surprise, the value of z
after the last bar showed to be 1.
This means that either:
var
variables are not persisted within a function (disproved by my previous question)- nested function calls have their own execution context.
Can't think of another reason for this behaviour.
Can someone confirm this, or maybe provide an alternate explanation?
//@version=4
study("PlayGround")
var int y = 0
var int z = 0
f1() =>
var int b = 0
b := b + 1
b
f2() =>
f1()
true
if true and f2()
y := y + 1
if barstate.islast
z := f1()
plot(y, title="y")
plot(z, title="z")