You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何For循环中出现索引6越界?Pine Script代码报错排查

Pine Script索引越界问题原因及修复方案

问题原因

  • arr_bool数组包含12个元素,原循环for i = 0 to array.size(arr_bool) - 1 by 2会让i依次取0、2、4、6、8、10。
  • 但arr_string数组仅6个元素,有效索引范围是0到5。当i=6时,执行array.get(arr_string, i)会访问超出数组长度的索引,直接触发"Index out of bounds"报错。
  • 核心逻辑偏差:你需要每两个arr_bool元素对应一个arr_string元素,但循环的终止条件未匹配两者的长度关系,导致i的取值超出了arr_string的合法索引范围。

修复方案

调整循环逻辑,让i的取值始终对应arr_string的合法索引,同时匹配arr_bool的成对元素:

//@version=5
indicator("TEST", overlay=true)

var tbl = table.new(position.top_right, 3, 6, frame_width=1, border_width=1, border_color=#0d14ec)

a = false
b = true
c = false
d = true
e = false
f = true
g = false
h = true
j = false
k = true
l = false
m = true

arr_bool = array.from(a, b, c, d, e, f, g, h, j, k, l, m)
arr_new_bool = array.new_bool(0)

arr_string = array.from('test 1', 'test 2', 'test 3', 'test 4', 'test 5', 'test 6')
arr_new_string = array.new_string(0)

// 调整循环:按arr_string的长度循环,每轮对应arr_bool的两个元素
for i = 0 to array.size(arr_string) - 1
    bool_idx_1 = i * 2
    bool_idx_2 = bool_idx_1 + 1
    if array.get(arr_bool, bool_idx_1) or array.get(arr_bool, bool_idx_2)
        array.push(arr_new_string, array.get(arr_string, i))
        array.push(arr_new_bool, array.get(arr_bool, bool_idx_1))

if barstate.islast
    if array.size(arr_new_string) > 0
        for i = 0 to array.size(arr_new_string) - 1
            table.cell(tbl, 0, i, text=str.tostring(array.get(arr_new_string, i)) + ' ' + str.tostring(array.get(arr_new_bool , i)), text_color=color.white, bgcolor=#0d14ec)

内容的提问来源于stack exchange,提问作者zollen 123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 10:40:00