Re: [Vala] Idle.add lambda function with local variable



Ok I messed up that example, sorry. Obviously in my
real project I do
create a main loop. Don't have time now, but unless
someone can help me
despite my bad example I'll post the real code from my
project later.

Well, the point is not whether the main loop is created,
but whether it's
actually dispatching. If you call the Thread.usleep() from
within a main loop,
no idle handlers are going to run, because you didn't
return to the main
loop, so it can't do it's job. You have to return from the
currently
executing handler and than the idle handlers can run (the
event dispatching
is completely synchronous -- until one is completely
handled, no other can
be).

Newer vala (since 0.7.7 IIRC) allows writing a single
"async" function, that
will be automatically split into parts that can be run from
the mainloop at
separate events, but you need to understand how the main
loop behaves before
you can use them anyway.

Thanks Jan, for that additional info. There are indeed still one or two things about threading that I could 
use some more practice with.

However, in the program I'm writing threading isn't the problem. I was wondering about using local variables 
in a lambda function, with the purpose of using them in a function that is added to Idle.

So now wrote a new (better) example and found out that it actually works:


public class Main : Object {

  public class MyObject : Object {
    public int x { get; set; }
  }

  public static void button_clicked () {
    MyObject o = new MyObject ();
    o.x = 3;
    Idle.add ( () => {
      print_myobject (o);
      return false;
    });
  }

  public static void print_myobject (MyObject o) {
    print ("%d\n", o.x);
  }

  public static int main (string[] args) {
    Gtk.init (ref args);

    Gtk.Button button = new Gtk.Button.with_label ("Click me");
    button.clicked.connect (Main.button_clicked);

    Gtk.Window window = new Gtk.Window (Gtk.WindowType.TOPLEVEL);
    window.destroy.connect (Gtk.main_quit);
    window.add (button);
    window.show_all ();

    Gtk.main ();
    return 0;
  }
}


The above works, it prints "3" everytime you click the button. However, when compiling, it still gives the 
error I posted about in my original post:


/media/Data/Code/Vala/valatest/lambda/main.vala.c: In function ‘main_button_clicked’:
/media/Data/Code/Vala/valatest/lambda/main.vala.c:131: warning: passing argument 4 of ‘g_idle_add_full’ from 
incompatible pointer type
/usr/include/glib-2.0/glib/gmain.h:291: note: expected ‘GDestroyNotify’ but argument is of type ‘void 
(*)(struct Block1Data *)’


I assumed I was doing something wrong when I saw this, but since the compiled program does work fine, I'm 
starting to think it's just a small bug in Vala.






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