Re: [Vala] static string variable is empty!





On Tue, January 5, 2010 13:12, Frederik wrote:
Non-value-type static class variables are only initialized after the
class was instantiated at least once. This behaviour is a little bit
counter-intuitive, and I hope it will change in the future.

I have to disappoint you -- that behaviour can't change.

The problem is, that the while the mechanism for static constructors
exists for C++, there does not seem to be a portable way to use it from
C (in gcc you can use the __attribute__((constructor)), but that's an
extension).

You have several options:

- create a throw-away instance:

  static int main (string[] args) {
      new Global ();
      stdout.printf ("all data is in: " + Global.dataDir);
      return 0;
  }

Actually, there is no need to do that -- calling typeof(Global); is enough.

- call a static initialization method:

  static int main (string[] args) {
      Global.init ();
      stdout.printf ("all data is in: " + Global.dataDir);
      return 0;
  }

This should not work. *static* methods do not cause a class to be
initialized (*class* methods do, though).

- make 'dataDir' const, if it is not intended to change

- make the variable a class one instead of static one.

public class Global {
    class string dataDir = "whatever";
}

-- 
                                        - Jan Hudec <bulb ucw cz>




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