On Sun, 08 Jan 2012 12:54:13 -0500, Ben Davis <[email protected]> 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!
My first inclination is to use pointers. D doesn't have -> operator, so
pointers are seamless for your small example:
auto tile = &map[y*w+x];
tile.id = something;
tile.isWall = true;
When you need to pass it to a ref function, or if you do any operators on
it, you would need to use *.
Another horribly inefficient option (if you don't use -inline) is this:
@property ref tile() { return map[y*w+x]; }
With new => syntax (in git head), this would probably be:
@property ref tile => map[y*w+x];
-Steve