Kaz Kylheku
5/30/2016 11:50:00 PM
On 2016-05-30, Eduardo V. <lalohao@gmail.com> wrote:
> El lunes, 30 de mayo de 2016, 7:33:15 (UTC-5), Jim Newton escribió:
>> On Monday, May 30, 2016 at 1:11:20 PM UTC+2, Eduardo V. wrote:
>>
>> > (loop for n from 8 downto 0 do
>> > (connect (checkbox :expand nil)
>> > (lambda (widget)
>> > (if (gtk-toggle-button-active widget)
>> > (format t "Pressed ~s.~%" n)
>> > (format t "Released ~s.~%" n))))))
>> >
>> > Am i missing something fundamental?
>> > Thanks in advance
>>
>> what happens if you change to the following?
>>
>> (loop for n from 8 downto 0 do
>> (connect (checkbox :expand nil)
>> (let ((n n))
>> (lambda (widget)
>> (if (gtk-toggle-button-active widget)
>> (format t "Pressed ~s.~%" n)
>> (format t "Released ~s.~%" n)))))) )
>
> That worked! Thank you
> Why did that work btw?
You're missing that loop is iterative; it doesn't instantiate a fresh
variable n for each iteration of the loop. This means that all the
lexical closures created by lambda capture the same variable n;
they do not see different environments.
The let construct introduces a new environment around each lambda
which is extended with a fresh binding for a new variable n
(which receives its value from the outer loop variable n,
and then shadows that outer n).
Each lambda then captures this this fresh environment.