Posted by
Pontus Östlund  -  May 2011
This is something I have wondered about for years, but I've never bothered finding a solution.

Say I have a class like this:

class Klass
  string name = "klass";
  mapping attributes = ([]);
  array values = ({});

  Klass parse_xml(string xml)
    /* ... */
    return this;

  mixed `[](string|int index)
    if (intp(index)) {
      if (has_index(values, index))
       return values[index];
      return 0;

    if (has_index(this, index))
      // Will cause recursion
      return this[index];

    return attributes[index];

  mixed `->(string|int index)
    return `[](index);

And you would (psuedo) use it like:

Klass obj = Klass()->parse_xml("my-xml-data");
// Would find the first index in obj->values
write("%O\n", obj[0]);
// Would find the index "type" in obj->attributes
write("%s\n", obj->type);

But the implementation in Klass will cause a stack overflow. Is there any way around this?
Posted by
Martin Stjernholm  -  May 2011
You need to use ::`[] or ::`-> to access the "real" indexing operations from your own overloaded variants:

   return ::`[] (index);
Posted by
Pontus Östlund  -  May 2011
Awesome! That's just too simple!
I tried with predef::`[](obj, index) with no result and wasn't aware of ::`[](index).

It's always nice to learn new stuff :)

Thanks a bunch!
Search this thread: