The way to do that in Pike currently is to overload `-> and `->=, but that has several disadvantages when it comes to inheritance. If it's possible to overload indexing for specific identifiers, it'd become much less of a problem. It could look like this:
int `->foo() {return foo;} void `->foo= (int value) {foo = value;}
Even if it doesn't solve the inheritance problem, this would be a nice addition imho. It's easier to write than full-blown `-> and `->=, if nothing else.
Footnote: I think it has been mentioned before, but the inheritance problem is this:
class Foo { // This class emulates an identifier foo private int value; mixed `-> (string index) { if (index == "foo") return value; else return ::`-> (index); } void `->= (string index, mixed val) { if (index == "foo") value = val; else ::`->= (index, val); } }
class Bar { inherit Foo; void f() { foo = 17; // Error - the inherited identifier is not really there. } }
The identifier specific `->foo and `->foo= could solve that too, but then they're not really overload functions for -> and ->= anymore.
/ Martin Stjernholm, Roxen IS
Previous text:
2003-12-20 10:24: Subject: C#-like properties
While working on my master thesis, I have once again discovered the many similarities between C# and Pike. With the C# spec 2.0, C# will become even more Pike-like and for example introduce lambda expressions.
At present, there is one thing in C# which I would very much like to see in Pike.
C# has a concept called property. It's a mix of a variable and methods to get and set that variable.
It is considered good OO-practise to hide variables and use methods to access them but this causes a lot of polution within the namespace of a class with a log of variables if each one must have a getFoo() and a setFoo() method. Here is how to do it the C# way:
private int foo; public int Foo { get { return foo; } set { foo = value; } }
To access the Foo property, one just uses it just like a normal variable:
int x = Foo; Foo = x+1;
C# appears to implement this by turning the property into two methods, which in the example above would be called get_Foo() and set_Foo(). These methods cannot be called directly by the code, attempts to do so causes a compilation error.
In my sample, there is not much use in having a property, since no processing of the value is done, but in real life situations, there are many times I found that I may want to limit the value set by the caller to a certain range or similar. This is easily done with properties in C#.
Ofcourse, the problem can be solved by implementing the get and set methods manually, as one does today, but I believe that the C# way is much better looking and, at least to me, feels more natural.
My suggestion is that we put implementation of a C#-like property concept on the TODO-list. Thoughts, other ideas?
/ Marcus Agehall (Scanian)