There are examples of this technique all over this Q&A Forum. But I can appreciate the concept of having a template that does this so folks inclined to write their code are able to adapt it to their own needs. The technique is called "Recursion". This is when a variable derives its current value based on its own value from a previous bar on the chart.
Here is the basic template, adapted from the example code you provided:
def signal = close crosses above Average(close, 50);
rec storedValue = if signal then close else storedValue[1];
plot checkValues = if signal then close < storedValue[1];
checkValues.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Explanation:
- Variable named "signal" is true when the close crosses above the 50 period simple moving average.
- Variable named "storedValue" checks each bar to see if "signal" is true and if so it captures the close of that bar and carries that value forward until it encounters another bar in which "signal" is true. This is the recursive element required to store a value for future use.
- Variable named "checkValues" plots an arrow when a it finds a new bar in which "signal" is true, but also checks of the close of the correct signal bar is less than the storedValue of the previous bar. We must use the [1] index with the storedValue variable because its value is also being reset on this current bar.
Screenshot shows the results. I have included some trend lines on there connecting each of the values the code is using in the comparison.
If you really want to learn how this works you will add the following line to the code so you see how the stored value is captured and carried forward, and more importantly when that value is updated:
plot test1 = storedValue;