January 11, 2012
"Nick Sabalausky" <a@a.a> wrote in message news:jej186$78q$1@digitalmars.com...
> "Ben Davis" <entheh@cantab.net> wrote in message news:jeinah$2pnj$1@digitalmars.com...
>> Hi,
>> Please excuse the cross-post with D.learn. People have been helpful there with workarounds, but I'm bringing it here in the hope that we can discuss a language enhancement.
>> So - could support for 'ref' local variables be added, or is there a reason not to? 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;
>> someFunctionThatTakesRefMapTile(tile);
> I *really* want the ability to do that sort of thing, although I think it should be an alias rather than a ref variable:
> MapTile[] map;    // It's a struct
> alias map[y*w+x] tile;
> tile.id=something;
> tile.isWall=true;
> someFunctionThatTakesRefMapTile(tile);

I'm wrong. Using alias would have totally different semantics from your example. We really should have both:

ref MapTile tileRef=map[y*w+x];
alias map[y*w+x] tileAlias;

assert(&tileAlias == &tileRef);
x++; // tileAlias now points to the next element, tileRef is unchanged
assert(&tileAlias == &tileRef + 1);

January 12, 2012
On Wed, 11 Jan 2012 16:49:35 -0600, Nick Sabalausky <a@a.a> wrote:

> "Ben Davis" <entheh@cantab.net> wrote in message
> news:jejkdm$16un$1@digitalmars.com...
>> Note that this is already supported (apologies if I've got the syntax
>> slightly wrong):
>> foreach (i, ref tile; map) { ... }
>> That's a local variable too. It could have instead been defined such that
>> "tile" is an alias for "map[i]", but that would be a little strange.
> That's a very good point.
> Technically, foreach is implemented such that its body is a function and the
> "i, ref tile" is the parameter list. But I think that's beside the point.

Given that enabling foreach's syntax for general D functions, i.e.

myLoop(i, ref tile; map) { ... }

has been discussed several times in this newsgroup, the fact that "i, ref tile" is the parameter list of a delegate is not beside the point.
January 12, 2012
On Wednesday, January 11, 2012 01:06:21 Ben Davis wrote:
> So - could support for 'ref' local variables be added, or is there a reason not to?

While I don't really care about having ref local variables (it's possible in C++, and I almost never use them there - const & is pretty much the only way that I use references in C++), I _am_ curious as to why we ended up with ref for function parameters and foreach variables but not local variables. My _guess_ would be because of how a large percentage of C++ users do what I do and only use references for const & parameters, but I don't know. I may have to go digging through the archives to see if an explanation was given anywhere.

- Jonathan M Davis
Next ›   Last »
1 2