www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How delegate context work?

reply Eko Wahyudin <eko.wahyudin yahoo.co.id> writes:
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.
Mar 16
parent Adam D. Ruppe <destructionator gmail.com> writes:
On Thursday, 16 March 2017 at 14:53:27 UTC, Eko Wahyudin wrote:
 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?
The compiler sees that you are going to reference the variable, and copies it to a heap buffer on function entry, so it uses that instead of the stack. That heap buffer is reused across the delegates which is why it doesn't swap out (this is the same as Javascript's vars, but different than JS's `let` and C# and other languages).
Mar 16