Given an Array A, for each element, store a capturing lambda in Array B. Later, invoke them, yielding the following erroneous results:
Code: Select all
A := [1, 2, 3]
B := []
for item in A
B.Push(() => MsgBox(item))
%B[1]%() ; MsgBox(''), expected MsgBox('1')
%B[2]%() ; MsgBox(''), expected MsgBox('2')
%B[3]%() ; MsgBox(''), expected MsgBox('3')
Introducing a temp variable yields the following:
Code: Select all
A := [1, 2, 3]
B := []
for item in A
{
temp := item
B.Push(() => MsgBox(temp))
}
%B[1]%() ; MsgBox('3'), expected MsgBox('1')
%B[2]%() ; MsgBox('3'), expected MsgBox('2')
%B[3]%() ; MsgBox('3'), expected MsgBox('3')
Reverting back to Func/Bind resolves the issue:
Code: Select all
A := [1, 2, 3]
B := []
for item in A
B.Push(Func('MsgBox').Bind(item))
%B[1]%() ; MsgBox('1'), expected MsgBox('1')
%B[2]%() ; MsgBox('2'), expected MsgBox('2')
%B[3]%() ; MsgBox('3'), expected MsgBox('3')