@@ -1230,15 +1230,18 @@ ex_while(exarg_T *eap)
12301230 {
12311231 scriptitem_T * si = SCRIPT_ITEM (current_sctx .sc_sid );
12321232 int i ;
1233+ int first ;
12331234 int func_defined = cstack -> cs_flags [cstack -> cs_idx ]
12341235 & CSF_FUNC_DEF ;
12351236
12361237 // Any variables defined in the previous round are no longer
12371238 // visible. Keep the first one for ":for", it is the loop
12381239 // variable that we reuse every time around.
1239- for (i = cstack -> cs_script_var_len [cstack -> cs_idx ]
1240+ // Do this backwards, so that vars defined in a later round are
1241+ // found first.
1242+ first = cstack -> cs_script_var_len [cstack -> cs_idx ]
12401243 + (eap -> cmdidx == CMD_while ? 0 : 1 );
1241- i < si -> sn_var_vals .ga_len ; ++ i )
1244+ for ( i = si -> sn_var_vals .ga_len - 1 ; i >= first ; -- i )
12421245 {
12431246 svar_T * sv = ((svar_T * )si -> sn_var_vals .ga_data ) + i ;
12441247
@@ -1250,6 +1253,12 @@ ex_while(exarg_T *eap)
12501253 // still exists, from sn_vars.
12511254 hide_script_var (si , i , func_defined );
12521255 }
1256+
1257+ // Start a new block ID, so that variables defined inside the
1258+ // loop are created new and not shared with the previous loop.
1259+ // Matters when used in a closure.
1260+ cstack -> cs_block_id [cstack -> cs_idx ] = ++ si -> sn_last_block_id ;
1261+ si -> sn_current_block_id = si -> sn_last_block_id ;
12531262 }
12541263 }
12551264 cstack -> cs_flags [cstack -> cs_idx ] =
0 commit comments