Dynamic D

Robert Jacques sandford at jhu.edu
Mon Jan 3 19:44:00 PST 2011


On Mon, 03 Jan 2011 22:19:49 -0500, spir <denis.spir at gmail.com> wrote:

> On Mon, 3 Jan 2011 22:23:29 +0000 (UTC)
> Adam Ruppe <destructionator at gmail.com> wrote:
>
>> Over the weekend, I attacked opDispatch again and found some old
>> Variant bugs were killed. I talked about that in the Who uses D
>> thread.
>>
>> Today, I couldn't resist revisiting a dynamic kind of object, and
>> made some decent progress on it.
>>
>> http://arsdnet.net/dcode/dynamic.d
>>
>> (You can compile that; there's a main() at the bottom of that file)
>>
>> It isn't quite done - still needs op overloading, and probably better
>> errors, but it basically works.
>>
>> It works sort of like a Javascript object.
>>
>> Features:
>>
>> opDispatch and assignment functions:
>> Dynamic obj;
>>
>> // assign from various types
>> obj = 10;
>> obj = "string";
>>
>> obj.a = 10; // assign properties from simple types naturally
>>
>> // can set complex types with one compromise: the () after the
>> // property tells it you want opAssign instead of property opDispatch
>> obj.a() = { writefln("hello, world"); }
>>
>> // part two of the compromise - to call it with zero args, use call:
>> obj.a.call();
>>
>> // delegte with arguments works too
>> obj.a() = delegate void(string a) { writeln(a); };
>>
>> // Calling with arguments works normally
>> obj.a("some arguments", 30);
>>
>>
>> Those are just the basics. What about calling a D function? You
>> need to convert them back to regular types:
>>
>> string mystring = obj.a.as!string; // as forwards to Variant.coerce
>>     // to emulate weak typing
>>
>> Basic types are great, but what about more advanced types? So far,
>> I've implemented interfaces:
>>
>> interface Cool {
>>     void a();
>> }
>>
>> void takesACool(Cool thing) { thing.a(); }
>>
>>
>>
>> takesACool(obj.as!Cool); // it creates a temporary class implementing
>> // the interface by forwarding all its methods to the dynamic obj
>>
>>
>>
>> I can make it work with structs too but haven't written that yet.
>> I want to add some kind of Javascript like prototype inheritance too.
>>
>>
>>
>> I just thought it was getting kinda cool so I'd share it :)
>
>
> Waow, quite cool, indeed! I'll have a look at your code as soon as I  
> can. Esp
> 	obj.a() = { writefln("hello, world"); }
> is a real mystery for me ;-)

Well, obj.a() returns by ref, which is how that works. The expression  
itself is a zero arg delegate literal.


More information about the Digitalmars-d mailing list