2

I can't seem to get values to store in a global array. Code example below:

strategy("Array Issue", overlay=true, margin_long=100, margin_short=100)
var vars = array.new_int(5)
var TRACK = 0

init() =>
     if (barstate.isfirst)
         array.set(vars, TRACK, 0)

run() =>
    var track = array.get(vars, TRACK)
    label.new(bar_index, high, str.tostring(track))
    var newTrack = track+1
    array.set(vars, TRACK, newTrack)
    var storedTrack = array.get(vars, TRACK)
    label.new(bar_index, low, str.tostring(storedTrack))

init()
run()

The "track" label is always 0 and the "storedTrack" label is always 1. So the array.set is working but not carrying over to the next call of run()

What am I doing wrong?

Holger Just
  • 52,918
  • 14
  • 115
  • 123
Sean Barnard
  • 59
  • 1
  • 1
  • 9

1 Answers1

0

var variables will be initialzed only once even if you have it in a function.

So, what's happening here is on the first bar track, newTrack and storedTrack are being initialized. But those lines will not be called again on the next executions. Therefore, their values never get updated.

Simply remove the var keyword.

In that case, only the first element of your array will be updated. That is because TRACK is always 0. So, array.set(vars, TRACK, newTrack) will always write to index 0.

vitruvius
  • 15,740
  • 3
  • 16
  • 26