title: How to create a variable that retains its value
body: <p>In thinkscript charts and scans, any script gets executed many times once for each bar. Program state between such executions is stored in array variables which are accessed directly or by an offset via <code>[]</code> or <code>GetValue()</code>. Many scripts involving some kind of pattern recognition need to initialize such variables at the first bar by assigning them initial values. When executing on subsequent bars, the script either copies the previous value or creates new values. Then depending on some other condition, the script may check whether the current array entry still equals the first array entry to discover whether something interesting happened in the data.</p>
  
  <p>The following test script follows this simple pattern. Its single purpose is to use the scanner to verify that the first entry of a single variable retains its value.</p>
  
  <p>A scan executes a single plot statement at the last bar. The script has as as the single criterion that the tested variable holds its value and is not changed by something else. Changing variables or variable array entries in thinkscript is illegal and should never happen. However, this script shows that the first entry of a variable gets overwritten. How does this happen, and how can it be avoided?</p>
  
  <pre><code>def index;
  def myVar;
  if (BarNumber() == 1) {
      index = -1;
      myVar = close;
  } else {
      if (close &gt; myVar[1]) {
          myVar = close;
          index = index[1];
      } else {
          if (close &lt;= myVar[1]) {
              index = 1;
          } else {
              index = index[1];
          }
          myVar = myVar[1];
      }
  }
  plot scan = GetValue(index, BarNumber() -1) == -1;
  </code></pre>