[Vala] Closures and local variables



Hi,

I'm still having hard time using closures in Vala.

If I understand it well, the following code should return two
lambda-expressions referencing the same variable ("Pair" is just a
container - as an attachment, I join the full code):
    Pair builder(int v) {
        return new Pair(
            () => { return ++v; },
            () => { return --v; }
        );
    }

Here is how I use the function above:
    void main() {
        Pair p1 = builder(10);
        Pair p2 = builder(100);
    
        stdout.printf("%d %d %d\n", p1.fa(), p1.fa(), p1.fb());
        stdout.printf("%d %d %d\n", p2.fa(), p2.fa(), p2.fb());
    }

There is no error on compilation. But the result is quite surprising:
    sh$ valac closure.vala 
    sh$ ./closure
    1 2 1
    1 2 1

It appears that each time "builder" is called, both returned
lambda-expressions are referencing the same variable. Which is a
different one for each call to "builder". That was expected.
But, for some reason, those variables are initialized to 0 instead of
the value passed as an argument.


I don't know if this is a good comparison, but I tried what I think is
the same code in JavaScript using Mozilla Rhino. The full code is
given at the end of this mail. This time, that gives me the result
I was expecting:
    sh$ rhino closure.js
    11 12 11
    101 102 101



Anyway, I think I missed an important point regarding how closures work
in Vala. So, I would be very glad if someone could bring me to some
explanations!


Thanks in advance,
- Sylvain

/********* closure.js *********/
function builder(v) {
    return { fa: function() { return ++v; },
             fb: function() { return --v; }
           }
}

p1 = builder(10);
p2 = builder(100);


-- 
Sylvain Leroux <sylvain chicoree fr>
http://www.chicoree.fr


Attachment: closure.vala
Description: Text Data



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