Copying a variable state in a delegate literal definition

Daniel Murphy yebblies at nospamgmail.com
Fri Sep 2 21:03:23 PDT 2011


"Andrej Mitrovic" <andrej.mitrovich at gmail.com> wrote in message 
news:mailman.2651.1315000369.14074.digitalmars-d-learn at puremagic.com...
> On 9/2/11, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>> Am I missing something, or is it this simple?
>>
>> void appendMenuButton()
>> {
>>     static size_t menuIndex;
>>     auto frameIndex = menuIndex++;
>>     button.connect!(Signal.MouseClick) = { this.showMenu(frameIndex); };
>> }
>>
>> -Steve
>>
>
> Actually It *is* that simple. Which is odd because I swear I've tried
> it once but it didn't work, and now it works again. Something has to
> be messing with the compiler or my brain!

It won't work when loops are involved.  In that case I usually use:
foreach(i; ...)
(int i){
   something = { delegate that uses i like a constant };
}(i); 




More information about the Digitalmars-d-learn mailing list