[DGD] Question: Implementing foreach()

Par Winzell zell at skotos.net
Tue May 3 16:32:01 CEST 2005


Trance Junkie wrote:

> Firstly, is there any particular reason why DGD doesn't have built-in
> foreach() functionality? At this point I am assuming it has for(), but I
> would have thought that foreach() would be quite useful in almost any
> multi-object server. Of course, I am just a lowly coder at this stage,
> so please bear with my apparent lack of a clue.

As Dworkin suggests, a foreach extension of LPC would be too magical as
long as there's no well-established idea of how iteration should occur
over datatypes that might change in the middle of the loop. I would also
 argue that it's a rather pointless extension, especially since LPC
won't declare and initialize a variable at the same time. I'm not at all
sure readability increases.

In the context of object types, it makes better sense. Arrays and
mappings are of limited size, after all, as are strings; I think a
modern Mud may well want to abstract most of their collections using
LWO's. This also helps with the mutable data problem. To take Java's new
foreach functionality as an example, classes in the Collections
framework will throw a ConcurrentModificationException if underlying
data changes mid-iteration.

So if a sane foreach design relies on specific mudlib classes, then
obviously the foreach implementation itself should be in the mudlib. To
do this, as Noah says, means you take over compile_object() and do your
own pass over the source code before you hand it over to DGD's compiler.
At that point you could (if you still cared enough) expand e.g.

  foreach (item : player->query_inventory()) {
      item->explode();
  }

to something like

  {
    object "/lib/iterator" __tmpiter345;
    __tmpiter345 = player->query_inventory()->get_safe_iterator();
    while (__tmpiter345->has_more()) {
      item = __tmpiter345->get_next();
      item->explode();
    }
  }


My personal opinion is increasingly that it's better to resist the lure
of syntactic sugar. Verbose code is not necessarily less readable, and
once you start modifying LPC, it's incredibly hard to resist bloating
the language.

Zell



More information about the DGD mailing list