简体   繁体   English

pine-script function 返回的值与预期不同

[英]pine-script function returns different value than expected

I am struggling with the understanding of function executions in pine-script.我正在努力理解 pine-script 中的 function 执行。 Please see the short script below, it should compile as it is:请参阅下面的简短脚本,它应该按原样编译:

//@version=4
study("My Script")
a = 100.
d = 100.

d:=nz(d[1]) + 10

f_(_src) => nz(_src[1]) + 10
a := f_(a)

plot(a, "a", color.red, 5)
plot(d, "d", color.yellow, 5)

I would expect, that the value of a and d are the same, as the function "f_" executes the same code as in the assignment for d .我希望ad的值是相同的,因为 function "f_" 执行与d的赋值相同的代码。 But a has always a constant value of 110 from the 2nd cycle, when d increases each cycle linearly +10.但是从第二个周期开始, a始终具有恒定值 110,此时d每个周期线性增加 +10。

What is the reason it behaves like this?它这样做的原因是什么? I would be very happy about some reference.我会很高兴有一些参考。

Thank you a lot for your help, Seb.非常感谢你的帮助,Seb。

a != d,d 的值线性增加,a 保持不变

Your variables are initialized to 100. on every bar.您的变量在每个柱上初始化为100.

For variable a :对于变量a

  • The value passed to f_() is always the a variable which has just been initialized to 100. , as it's initialized on every bar, but once inside the function, that current value isn't used.传递给f_()的值始终是刚刚初始化为100. a变量,因为它在每个柱上都被初始化,但一旦进入 function,则不使用当前值。 Because you use nz(_src[1]) , the value used is the value of the parameter the last time the function was called, all this from the function's perspective—not the global scope's perpective.因为您使用nz(_src[1]) ,所以使用的值是上次调用 function 时的参数值,所有这些都是从函数的角度来看的,而不是从全局范围的角度来看。
  • On the function's first call, the nz() call replaces the value with 0 as there is no previous value.在函数的第一次调用中, nz()调用将值替换为0 ,因为没有先前的值。 The function returns 10 . function 返回10
  • On the second bar and all subsequent ones, you are still calling the function with the a=100 argument, but from thereon a previous value exists for the argument inside the function.在第二个柱和所有后续柱上,您仍在使用a=100参数调用 function,但从那时起,function 中的参数存在先前的值。 It is always 100. because that's what you are calling the function with every time, so nz(_src[1]) always returns 100. , and the function always returns 110.它始终为100.因为这就是您每次调用 function 的原因,因此nz(_src[1])始终返回100. ,而 function 始终返回110.

For variable d :对于变量d

  • On the first bar there is no previous value so nz(d[1]) returns 0 and the value 0 + 10 = 10 is assigned to d .在第一个柱上没有先前的值,因此nz(d[1])返回0并将值0 + 10 = 10分配给d
  • On the second bar, nz(d[1]) returns 10 and the value 10 + 10 = 20 is assigned to d , and so on.在第二个柱上, nz(d[1])返回10并将值10 + 10 = 20分配给d ,依此类推。
  • In the case of d , the recently initialized value of 100. on each bar is, in fact, never used.d的情况下,实际上从未使用过每个柱上最近初始化的值100.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM