Pine Script库多输出使用及代码有效性技术问询
Pine Script库是否支持多输出?
问题说明
在Pine Script库中能否设置函数返回多个输出?以下示例函数是否有效:
export sorting_float(float[] Value, int[] BarIndex) => //{ var NewBarInd = array.new_int() ValueSorted = array.copy(Value) sortedLowsIndices = array.sort_indices(Value) array.sort(ValueSorted, order.ascending) Size = array.size(BarIndex) if Size>0 for i = 0 to Size-1 array.push(NewBarInd,array.get(BarIndex,array.get(sortedLowsIndices,i))) ValueSorted, NewBarInd
预期返回ValueSorted和NewBarInd两个数组,但使用以下代码调用时出现报错:
float[] output_1, int[] ouput_2 = mylib.sorting_float(Input_1, Input_2)
解答
Pine Script支持函数返回多个值,你的核心思路可行,但代码存在两处问题:
函数内部数组初始化错误:
你用var NewBarInd = array.new_int()声明数组,var会让数组在脚本生命周期内仅初始化一次,后续调用函数时会持续累积旧数据,导致结果异常。应改为每次调用都新建数组:export sorting_float(float[] Value, int[] BarIndex) => NewBarInd = array.new_int() // 移除var,每次调用重建数组 ValueSorted = array.copy(Value) sortedLowsIndices = array.sort_indices(Value) array.sort(ValueSorted, order.ascending) Size = array.size(BarIndex) if Size > 0 for i = 0 to Size - 1 array.push(NewBarInd, array.get(BarIndex, array.get(sortedLowsIndices, i))) [ValueSorted, NewBarInd] // 用方括号包裹多返回值,语法更规范调用语法错误:
接收多返回值时需用方括号包裹变量,同时注意拼写错误(原代码中ouput_2少写了一个t),正确调用方式如下:// 带类型声明的调用 [float[] output_1, int[] output_2] = mylib.sorting_float(Input_1, Input_2) // 自动推断类型的简化调用 [output_1, output_2] = mylib.sorting_float(Input_1, Input_2)
内容的提问来源于stack exchange,提问作者sey eeet
相关产品推荐
相关产品推荐

