Subject: Re: bug#63586: 29.x: dotimes (possible) problem

From: Stefan Monnier <[email-masked]>
Date: Fri, 19 May 2023 13:29:14 -0400

>> Basically: changing the value of the loop variable in the body of
>> dotimes does not seem to have any effect,

It does, but only within the current iteration, because the variable is
local to the iteration (each iteration gets a fresh new variable).

>> where for versions <29.x it used to.

Indeed it was changed last year for dynamically scoped ELisp to align it
with the semantics used in the lexically scoped ELisp dialect (and thus
simplify the macro).

>> Here is a minimal stretch of dummy code clarifying the problem I'm
>> reporting.
>>
>> emacs-29.0.91 (or 29.0.90)
>> ==========================
>>
>> (dotimes (ii 10)
>> (insert (format "%2d " ii))
>> (when (= ii 4)(setq ii 11))
>> )
>> ==>  0  1  2  3  4  5  6  7  8  9 
>>
>> emacs-28.2 (or any version <29.x)
>> =================================
>>
>> (dotimes (ii 10)
>> (insert (format "%2d " ii))
>> (when (= ii 4)(setq ii 11))
>> )
>> ==>  0  1  2  3  4 
>
> I can only reproduce the behavior you see in 28.2 in Emacs 26.3.  All
> the later versions, starting from 27.1, behave like Emacs 29 does.

AFAIK what the OP describes is new in Emacs-29 (commit
c6c9dfc8670f5698634a8d5853853056ff928974).
But the change only affects code that has not activated
`lexical-binding`: for `lexical-binding`, the behavior has been with us
"forever" (i.e. since Emacs-24, when `lexical-binding` was introduced).

>> AFAICS, changing the value of the loop variable from inside the loop
>> body is supported by any other language which I know about

It's definitely not supported by Common Lisp, which explicitly allows
both our old implementation and our new implementation (i.e. code like
yours may or may not work depending on the CL implementation).
Several other languages (starting with Pascal :-) either disallow or
discourage modifying the iteration variable(s) inside the loop body.

But in any case, the question is not whether it's a good idea or not: it
used to happen to work and now it doesn't work any more.

Maybe we should mention the change in etc/NEWS?

        Stefan