如何在K线周期间持久化UDT对象内的数组数据?
问题
我正在开发一个包含多个UDT的Pine Script指标,其中部分UDT包含可在每个tick动态增删的其他UDT数组。采用以下代码模式开发:
type TDetail int oneThing int anotherThing // This has a collection of TDetail objects. type TMaster array<TDetail> details = na // Some sort of factory function. createMaster() => array<TDetail> details = array.new<TDetail>() TMaster result = TMaster.new(details=details) result // Initialize the master object only once. var TMaster master = createMaster() // Some logic on every tick... if (someConditionIsTrue) TDetail detail = TDetail.new(oneThing=1, anotherThing=2) // 示例属性值 master.details.push(detail)
但发现数组中的数据无法在tick间持久化,调试时数组始终为空,请问遗漏了什么?
解决方案
- 问题核心:Pine Script中,UDT的数组属性是值传递,直接调用
master.details.push(detail)时,你操作的是原数组的临时副本,修改不会同步回原UDT对象的details属性。 - 修复方法:将修改后的数组重新赋值给UDT的属性,替换原有的数组引用:
将代码中的master.details.push(detail)替换为:master.details := array.push(master.details, detail) - 原理:
array.push()方法会返回修改后的数组,通过:=赋值操作,把这个更新后的数组重新绑定到master.details,这样UDT对象才会持有最新的数组引用,数据才能在tick间持久化。
内容的提问来源于stack exchange,提问作者Italo Gomes
相关产品推荐
相关产品推荐

