Ref local variables?

simendsjo simendsjo at gmail.com
Sun Jan 8 11:27:58 PST 2012


On 08.01.2012 18:54, Ben Davis wrote:
> Hi,
>
> Is there a reason 'ref' is disallowed for local variables? I want to
> write something like:
>
> MapTile[] map; // It's a struct
>
> ref MapTile tile=map[y*w+x];
> tile.id=something;
> tile.isWall=true;
>
> My actual case is more complicated, so inlining the expression
> everywhere would be messy. I can't use 'with' because I sometimes pass
> 'tile' to a function (which also takes it as a ref). I don't want to
> make it a class since the array is quite big and that would be a lot of
> extra overhead. For now I'm using pointers, but this is forcing me to
> insert & or * operators sometimes, and it also reduces the temptation to
> use 'ref' in the places where it IS allowed, since it's inconsistent.
>
> I hope it's not a stupid question - it's my first one - but I couldn't
> find an answer anywhere. I like most of what I've seen of D so far, and
> I'm very glad to be able to leave C and C++ (mostly) behind!
>
> Thanks,
>
> Ben :)

I got something working, but only when using templates. Take the 
following with a grain of salt as I'm a newbie myself.

struct MapTile {
     string id;
}

enum w = 80, h = 25;
MapTile[w*h] map;

ref MapTile getTile(int x, int y) {
     return map[y*w+x];
}

void f(T)(ref T tile) {
     tile.id = "f()";
}

void g(ref MapTile tile) {
     tile.id = "g()";
}

void main() {
     // You can use auto ref return to set values directly
     getTile(10,10).id = "a";
     assert(getTile(10,10).id == "a");

     // And using templated ref arguments, you can pass by reference
     // note that I need to take the reference even when
     // using auto ref return
     auto tile = &getTile(1,1);
     f(tile);
     assert(tile.id == "f()");

     // But you'll need a dereference if not using a template
     g(*tile);
     assert(tile.id == "g()");

     assert(getTile(1,1).id == "g()");
}



More information about the Digitalmars-d-learn mailing list