Search code examples
arrayspropertiesd

How to make set property for an array?


I have:

@property float x(float[2] vector)
{
    return vector[0];
}

@property void x(float[2] vector, float value)
{
    vector[0] = value;
}

I can declare an array, for example float[2] a; and later get the first element of the array by simply calling a.x, but if I want to set a[0], I can't call a.x = 3.14. It does not cause problems to the compiler nor throws an exception. And later when I get a[0] it says it is NaN which is float.init. This means that a[0] was never set and a.x is valid and invalid at the same time.

I simply want a float array and have a get and set property x. Is there a way to do that? And I know that I can use a.x(3.14) for setting a[0], but I want to make it as if x is a member property of a.


Solution

  • Static arrays are passed by value. You need to use ref to pass by reference:

    @property float x(ref float[2] vector)
    @property void x(ref float[2] vector, float value)
    

    Note: I'm referring to D2. AFAIK in D1 static arrays used to be passed by reference, but in D2 they're passed by value by default.