Home > OS >  Loop an array push with a function in pine script
Loop an array push with a function in pine script

Time:12-12

I'm using pine script and I'm getting different results while doing an array push inside or outside a while loop.

Let's say I have a simple function that returns the sum of two values:

myFunction(myValue1, myValue2) => 
    myValue3 = myValue1   myValue2

And an array that will store the function's result:

myArray = array.new_float(0)

If I apply multiple array pushes like this:

array.push(myArray, myFunction(1, 0))
array.push(myArray, myFunction(1, 1))
array.push(myArray, myFunction(1, 2))
array.push(myArray, myFunction(1, 3))
array.push(myArray, myFunction(1, 4))

myArray correctly stores the following values:

myArray = [1, 2, 3, 4, 5]

Then I tried the same thing but with the array push inside a while loop:

myInc = 0
while myInc <= 4
    array.push(myArray, myFunction(1, myInc))
    myInc  = 1

And it did not store the same values in the array:

myArray = [1, 1, 1, 1, 1]

How can I correctly achieve an array push with a function inside a while loop?

CodePudding user response:

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

myFunction(myValue1, myValue2) => myValue3 = myValue1   myValue2

myArray = array.new_float(0)

// array.push(myArray, myFunction(1, 0))
// array.push(myArray, myFunction(1, 1))
// array.push(myArray, myFunction(1, 2))
// array.push(myArray, myFunction(1, 3))
// array.push(myArray, myFunction(1, 4))

var int myInc = 0

myInc := 0
while myInc <= 4
    array.push(myArray, myFunction(1, myInc)) 
    myInc  = 1

if barstate.islast
    label.new(bar_index, high, array.join(myArray, ',') )
  • Related