Vala quastion - List of Point Structures

I’m newbee in Vala. I need to create a multi-dimensional array (Ye ye, the one that is not supported, by the Vala guide for Java programmers). I decided to make a List of structures. And now I can’t get access to the field of the created structure.

void drawObject(int x, int y){print(@"x = $x\ty = $y");}

struct Point {
    public int x;
    public int y;

    public Point (int x, int y) {
        this.x = x;
        this.y = y;
    }
    public void print () {
        stdout.printf (@"($(this.x)\t$(this.y))\n");
    }
}

int main(string[] args) {

Point[] a={Point(1,1),Point(2,2),Point(3,4)};a+=Point(4,5);
print(@"$(a[0].x)\n") // ->1
var list = new List<Point[]>();
list.append(a);list.append(a);
Point[] b = list.index(0);
/*error */
int a = b[0].x;
print(@"$a\n");

return 0;
}

Error

console.vala:41.28-41.28: error: Argument 1: Cannot convert from `int' to `unowned Point[]'
    Point[] b = list.index(0);

It’s as if it wants the array index I specified the type Point.

GLib.List is a wrapper for GList, a linked list. It is mainly used in Vala when C APIs return it (e.g. Gtk.Container.get_children()). In any case, List.index() is used to find the index of an element, not to get the element at an index. You can access the element of the current link at list.data and the next link at list.next. Also note that an empty list is just null.

You cannot use an array as a generic type in Vala. One workaround is to wrap the array in a struct or class:

class PointArray {
    public Point[] points;
}

int main(string[] args) {
    var a = new PointArray ();
    a.points = { Point(1,1), Point(2,2), Point(3,4) };
    a.points += Point(4,5);
    print(@"$(a.points[0].x)\n"); // ->1
    var list = new List<PointArray>();  // Could have used List<PointArray> list = null;
    list.append(a);
    PointArray b = list.data;
    int c = b.points[0].x;
    print(@"$c\n");

    return 0;
}

However, I would use the data structures in libgee instead of GLib.List or the builtin arrays.

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.