Pine script PineScript-函数内未获取全局范围变量

Pine script PineScript-函数内未获取全局范围变量,pine-script,Pine Script,例如,以下脚本: //@version=4 study("sample") func(val)=> label l1= label.new(bar_index, high, text=tostring(val[2]), style=label.style_circle) trigger_condition = barstate.islast if(barstate.islast) func(close) 结果总是显示nan。原因是什么?将xyz[2]

例如,以下脚本:

//@version=4
study("sample")
func(val)=>
    label l1= label.new(bar_index, high, text=tostring(val[2]), style=label.style_circle) 
trigger_condition = barstate.islast
if(barstate.islast)
    func(close)

结果总是显示
nan
。原因是什么?将
xyz[2]
更改为
xyz[2]
都不起作用。

您的问题不是函数作用域中全局变量的可见性,因为函数使用的值作为参数传递给它

代码的工作方式与预期不同,因为您只调用了数据集最后一个栏上的函数,而且由于这是第一次调用,因此在创建标签时没有可参考的
val
的历史值

解决方案是在每个条上执行函数。这段代码显示了两种等效的方法,第二种是最有效的。请参见代码中的注释:

//@version=4
study("sample")

func1(val)=>
    // Create label on first bar.
    var label l1 = label.new(bar_index, high, "", style=label.style_circle)
    // Redefine label's position and text on each bar.
    label.set_text(l1, tostring(val[2]))
    label.set_xy(l1, bar_index, high)

func2(val)=>
    // Track history of the values on every bar but do nothing else.
    _v = val[2]
    if barstate.islast
        // Create label on last bar only.
        l1 = label.new(bar_index, high, tostring(_v), style=label.style_circle)

func1(close)
[编辑:2020.09.15:26-LucF]
第三个等价物示例,说明要回答的注释中的注释:

func3(_val)=>
    if barstate.islast
        // Create label on last bar only.
        l1 = label.new(bar_index, high, tostring(_val), style=label.style_circle)

func3(close[2])
此方法也会起作用,因为历史缓冲区的当前默认值为250可确保在偏移量2处存在关闭值:

if barstate.islast
    label.new(bar_index, high, tostring(close[2]), style=label.style_circle)

我编辑了答案,展示了两个相同的例子来说明我们的观点。希望这有助于澄清问题。不,作为参数传递给函数的变量不是作为值传递的,而是作为序列传递的。但是,序列值并不意味着序列的历史记录已填充。为了填充函数中使用的系列的历史记录,必须在每个栏上调用它。我的意思是:谢谢你的回答。我认为,在pinescript文档中应该提到这一点,当讨论“函数”如何工作时,所有这些示例(包括我的pastebin示例)都会在usrman中解释动态。同样,您的pastebin示例不起作用,因为您没有在每个条上调用函数,因此在其局部范围内没有历史记录,无论是对于
x
还是
y
还是您将在该局部范围内使用的任何其他变量。