Search code examples
pine-scriptpine-script-v5

How do you check whether 2 conditions are true or false in an array?


there,

I've been trying for several hours to make a loop to check if one of the first 2 elements of the array are true.

I would like to check if "a" or "b" of the array "arr_bool" is true and if it is then write the word "TEST" in the array "arr_string".

Basically, check 2 by 2 whether (a or b), (c or d), (e or f) are true or false.

Do you have an idea?

My last test is this:

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

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


a = false
b = true
c = false
d = true
e = false
f = true


arr_bool = array.from(a, b, c, d, e, f)
arr_string = array.new_string(0)


for i = 0 to array.size(arr_bool) - 1
    if(array.get(arr_bool, i) or array.get(arr_bool, i+1))
        array.push(arr_string, 'TEST')

if barstate.islast
    for i = 0 to array.size(arr_string) - 1
        table.cell(tbl, 0, i, text = str.tostring(array.get(arr_string, i)), text_color = color.white, bgcolor = #696969)

Solution

  • You can define the incremental step of the for loop with the by keyword. You just need to increase your step by 2.

    Below code assumes the length of the array is an even number. If that is not guaranteed, you need to add an additional check.

    //@version=5
    indicator("TEST", overlay = true)
    
    var tbl = table.new(position.top_right, 3, 6, frame_width  = 1, border_width = 1, border_color = #696969)
    
    a = false
    b = false
    c = false
    d = true
    e = true
    f = false
    g = true
    h = true
    
    arr_bool = array.from(a, b, c, d, e, f, g, h)
    string s = ""
    
    len = array.size(arr_bool)
    
    for k = 0 to len - 1 by 2
        _first = array.get(arr_bool, k)
        _second = array.get(arr_bool, k + 1)
    
        s := s + "[" + str.tostring(k) + "]: " + str.tostring(_first) + " OR "  + "[" + str.tostring(k + 1) + "]: " + str.tostring(_second) + " is: " + str.tostring(_first or _second) + "\n"
    
    if (barstate.islast)
        label.new(bar_index, high, s)
    

    enter image description here