tag:blogger.com,1999:blog-1368731483244051508.post4062715509895561187..comments2008-04-08T21:55:18.575+10:00Comments on while(nan): Fakin' closuresDkhttp://www.blogger.com/profile/02909587337938463354noreply@blogger.comBlogger4125tag:blogger.com,1999:blog-1368731483244051508.post-15127488146688861672008-04-08T21:55:00.000+10:002008-04-08T21:55:00.000+10:00I used a mixin-expression and a ctfe-function to g...I used a mixin-expression and a ctfe-function to generate something along the lines of:<BR/><BR/>string var1 = "i am the context";<BR/>int var2 = 5;<BR/><BR/>&( ((new class Object {<BR/> this(string var1, int var2) { /* ... */ }<BR/> void run() {<BR/> /* closure body pasted here */<BR/> }<BR/>})(var1, var2) ).run );<BR/><BR/>which is also really safe but very complicated to implement and not that easy to use because you have to write the function body inside a string and have to explicitely select the variables you want to "import".<BR/><BR/>-- asmanianAnonymousnoreply@blogger.comtag:blogger.com,1999:blog-1368731483244051508.post-63574299097648498852007-11-29T09:26:00.000+11:002007-11-29T09:26:00.000+11:00I'm affraid it doesn't work at all.With compiler v...I'm affraid it doesn't work at all.<BR/><BR/>With compiler v1.010, it would work as intended in debug mode but not in release, giving 15, 42, 165. As for v1.024, both debug and release give 15, 42, 165.Anonymousnoreply@blogger.comtag:blogger.com,1999:blog-1368731483244051508.post-9975150392539559762007-08-29T01:28:00.000+10:002007-08-29T01:28:00.000+10:00Cool; that approach is probably a lot safer than m...Cool; that approach is probably a lot <EM>safer</EM> than mine is.<BR/><BR/>To be honest, I'd be much happier if delegates grew some kind of .dup method, but there you go.Dkhttp://www.blogger.com/profile/02909587337938463354noreply@blogger.comtag:blogger.com,1999:blog-1368731483244051508.post-88366420523267019752007-08-29T01:27:00.000+10:002007-08-29T01:27:00.000+10:00Here's how you would do something similar using th...Here's how you would do something similar using the Tools package from scrapple:<BR/><BR/>xt4100 ~/d $ cat test2.d && echo "------" && gdc test2.d -o test2 scrapple/trunk/tools/tools/*.d -Iscrapple/trunk/tools && ./test2<BR/>module test2;<BR/>import std.stdio, tools.ext;<BR/>void delegate() make_dg(uint *target, uint what) {<BR/>return (ref uint *t, ref uint w) { *t=w; }~fix(target, what);<BR/>}<BR/><BR/>void main() {<BR/>uint f;<BR/>auto fn1=make_dg(&f, 42);<BR/>auto fn2=make_dg(&f, 1701);<BR/>f=15; writefln(f);<BR/>fn1(); writefln(f);<BR/>fn2(); writefln(f);<BR/>}<BR/>------<BR/>15<BR/>42<BR/>1701<BR/>The disadvantage is that you need to explicitly specify the external values you want to use. The advantage is that it stays away from the stack (or is that a disadvantage?)<BR/>std.bind works too, although I'd say that your trick has the advantage of being significantly neater. :)<BR/><BR/>--downs (who, coincidentally, wrote the tools package ^^)downsnoreply@blogger.com