How delegate context work?

Eko Wahyudin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Mar 16 07:53:27 PDT 2017


I'm writing promise library, and perform testing like this..


	app = new Application();
	Promise p = app.exec(delegate void(){ // first delegate
			write("Hello");
			std.stdio.stdout.flush;
			int xxx = 777;
			auto p2 = app.exec!int(delegate int(){ // second delegate
					return xxx;
			});

			p2.success = delegate void(int result){
				writefln("We got result:%d",result);
			};
		});
	with(p){
		success = delegate void(){
			writeln(" world");
		};
	}

	app.run();

When the my library executing second promise, Supprisingly I got 
amazing result, I can do same thing that javascript can do.

I printed "We got result:777".

My question is, on seconds delegate.

How D access xxx variable? where context pointer refer to?
How D keep xxx variable persistent?
Why xxx is not swapped out when we leave first delegate?

isn't that if we leave first delegate we execute RET n (on intel 
processor) and make the stack available for another call? so xxx 
memory address used by another function?

how this magic thing happen? or i just lucky got uncertain value 
but the value is 777 ?


Thank you guys, before.


More information about the Digitalmars-d-learn mailing list