Evaluate loop variables in the correct scope (#14067)

Change-Id: Ib5c2ed6f8738acc74b8ca82fdf309b9dbf1603a9