[Vala] anonymous structs or something similar?



Hi,

in C, I often used "anonymous structs" to make some functions simpler and easy
to extend and I would really like to do something similar in vala. The point
is to move functionality into a nice data "table" instead of a very long and
clumsy series of if's and lots and lots of repeated code

To illustrate what I mean, here is an example (c99):

---------------------------------------------------------------------
int myfunc(char *str, int val)
{
  struct {
    char  *name;
    int   data;
  } table[] = {
    {"foo", 1},
    {"bar", 2},
    {"baz", 3},
    {"abc", 4},
    {"123", 5},
    {NULL, NULL, 0}
  };
  static int DEFAULT_DATA = -1;
  for (int i = 0; table[i].name; i++) {
    if (strcmp(str, table[i].name) == 0) {
      return some_fancy_function(val, table[i].data);
    }
  }
  return some_fancy_function(val, DEFAULT_DATA);
}
---------------------------------------------------------------------
(21 lines)

I know I can do roughly the same in vala, but I would have to create new struct
type, define struct "constructor" and in general it will be longer, there will
be new struct polluting namespace and the solution lacks the simple elegance
of the C version.

Here's the example of how I have to do it in vala now:
---------------------------------------------------------------------
struct TableItem {
  public string name;
  public int    data;
  public TableItem(string a, int b) {
    name = a;
    data = b;
  }
}
int myfunc(string str, int val)
{
  TableItem[] table = {
    TableItem("foo", 1),
    TableItem("bar", 2),
    TableItem("baz", 3),
    TableItem("abc", 4),
    TableItem("123", 5)
  };
  const int DEFAULT_DATA = -1;
  foreach (var ti in table) {
    if (ti.name == str) {
      return some_fancy_function(val, ti.data);
    }
  }
  return some_fancy_function(val, DEFAULT_DATA);
}
---------------------------------------------------------------------
(25 lines)

Here's the example of how I'd like to be able to do it in vala:
---------------------------------------------------------------------
int myfunc(string str, int val)
{
  struct {
    public string name;
    public int    data;
  } table[] = {
    {"foo", 1},
    {"bar", 2},
    {"baz", 3},
    {"abc", 4},
    {"123", 5}
  };
  const int DEFAULT_DATA = -1;
  foreach (var ti in table) {
    if (ti.name == str) {
      return some_fancy_function(val, ti.data);
    }
  }
  return some_fancy_function(val, DEFAULT_DATA);
}
---------------------------------------------------------------------
(20 lines)

Is this or something close to this possible somehow in vala?

Thanks for any help or suggestion


Regards,
Jan Spurny



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]