0

Is there any way that Vala supports Self Invoking? Either with a class, or with a method?

Javascript supports self invoking like below. Which is what im looking for.

   (function(){
   // some code…
   })();

I'm attempting to load a class into a hashmap for dynamically loading.

Chris Timberlake
  • 490
  • 4
  • 16
  • Vala has delegates and closures. You can store an anonymous function in a delegate and invoke that delegate later. You can store a delegate in a hash map. Does that help? What exactly do you mean with `dynamical loading`? – Jens Mühlenhoff Oct 21 '13 at 13:29
  • Dynamic Loading meaning storing it in a hashtable for later then calling it by it's event name. I'm essentially looking for a class that automatically adds itself to a hashtable without being called. – Chris Timberlake Oct 22 '13 at 13:14

1 Answers1

0
using Gee;

[CCode (has_target = false)]
delegate void MyDelegate();

int main() {
        var map = new HashMap<string, MyDelegate>();

        map["one"] = () => { stdout.printf("1\n"); };
        map["two"] = () => { stdout.printf("2\n"); };

        MyDelegate d = map["two"];
        d();
        return 0;
}

If you need a target in your delegate you have to write a wrapper, see this question: Gee HashMap containing methods as values

As you can see, you don't need self invokation. Self invokation would look something like this:

int main() {
        (() => { stdout.printf("Hello world!\n"); })();
        return 0;
}

This is not supported by Vala (I tested this with valac-0.22).

Invoking a delegate var works as expected:

delegate void MyDelegate();

int main() {
        MyDelegate d = () => { stdout.printf("Hello world!\n"); };
        d();
        return 0;
}
Community
  • 1
  • 1
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113