It is obviously wrong because you did not read this:
http://www.amibroker.com/guide/h_understandafl.html
Index [ 0 ] in AFL represents FIRST array element (the OLDEST), not the LAST (latest).
You are coming from other platform apparently (like Tradestation) that uses reverse logic (i.e. 0 index is "latest").
In AmiBroker close[ 0 ] is the OLDEST bar in the database. In AmiBroker Bar number, like time, INCREASES.
The most recent bar (latest) is close[ BarCount - 1 ]
The second most recent bar is close[ BarCount - 2]
Again, reading this http://www.amibroker.com/guide/h_understandafl.html is ESSENTIAL.
The second thing you mentioned, BarCount is a NUMBER (scalar), not array, it represents the number of bars in the array, not the bar index as you assumed.
If you want to display bar index, you should use BarIndex() (nomen omen) function
And you MUST really read this
http://www.amibroker.com/guide/h_understandafl.html
The statement like this:
Condition=
i= ValueWhen(Condition,BarCount,1); // INCORRECT
CurrentBarClose = Close[i]; // INCORRECT
is incorrect on two levels. It uses BarCount instead of BarIndex in ValueWhen call. And it ignores the fact that ValueWhen is array function, returns ARRAY and as such can be used as index http://www.amibroker.com/guide/a_mistakes.html
You should be writing
CurrentBarClose = ValueWhen( Condition, Close, 1 );
(single line like this is doing everything you wanted to do in 3 lines)
The key thing to understand that pretty much all variables are ARRAYS, not scalars.
You work on arrays in parallel.
If you want to work with scalars sequentially (the "old" way like non-array languages work) you need to write a LOOP (like in "old" languages) that iterates thru array elements. So either you write array code and use array functions (like ValueWhen) and process arrays at once in single call or you do "old school" and write looping code (like in 'old' languages) and do things sequentially for each bar.
So either this (array code):
CloseWhenConditionIsMet = ValueWhen( Condition, Close );
or this (looping code with old school index-wise access)
for( i = 0; i < BarCount; i++ )
{
if( Condition[ i ] )
CloseWhenConditionIsMet [ i ] = Close[ i ];
else
if( i > 0 )
CloseWhenConditionIsMet [ i ] = CloseWhenConditionIsMet [ i - 1 ]; // keep previous
}
As you can see array code is whole lot shorter than old-school looping.