问题
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")
回答1:
Different instances of a call to the same function each maintain their own context, as you surmised. So in your case, the call to f1()
from within f2()
maintains a different context than the one made from within the if barstate.islast
block.
This has both advantages and disadvantages. It entails a persistent variable (i.e., initialized with var
) local to a function's scope cannot be shared by calling the same function from 2 different places in the script, but it allows repeated use of a function in a context like the 3 consecutive f_print()
calls in the second example here.
We are discussing persistent vars here, but the concept extends to the series values created by function calls, and so the values retrieved when using the history-referencing operator on local variables, as is explained here in the usrman.
来源:https://stackoverflow.com/questions/61688881/nonpersistance-of-var-initializations-in-functions