Dear all
I am analysing the Mata code behind a command (fairlie) in order to understand what actually this is doing, and I have arrived to a part of the script which works unexpectedly in my terminal. A simplified version of the problematic part is:

Code:
mata
mata clear
        for (j=1; j<=3; j++) {
            printf("{result}%1.0fc\n",j)

            if (j==1) {            
                xl = (10\8\7)
                xl
            }
            else {
                xl=xr
                xl
            }
            if (j==3) {
                xr=(8\7\6)
                xr
            }
            else {
                xr = xl
                xr
            }
            
        }
                
end
After running this, the program issues the following run-time error

<istmt>: 3499 xr not found

I think it fails to recognize that the last else statement should be executed in the first iteration, when j==1, which defines xr and pass it on for the second iteration, when j==2. What puzzles me is that in Stata the equivalent code actually works

Code:
        foreach j of numlist 1/3 {
            display as result "`j'"

            if (`j'==1) {
                matrix xl = (10\8\7)
                matrix list xl
            }
            else {
                matrix xl=xr
                matrix list xl
            }
            if (`j'==3) {
                matrix xr=(8\7\6)
                matrix list xr
            }
            else {
                matrix xr = xl
                matrix list xr
            }
            
            display _n(2)
            local ++j    
        }
Can somebody tell me what is wrong in the code above? Do Mata and Stata understand differently the if and else branching? Note that the program was written in version 9.2 but I am controlling this with version control in my PC (I don't think this may make a difference, though)
Thank you

JM
Stata 14.0