Closures

Capture a variable

var n

func todo() {
    n = 20
}

todo()
puts n    // 20

// todo

Another interesting example:

func makeAdder(x) {
    return (y) => {
        return x + y
    }
}

var add4 = makeAdder(4)
var add20 = makeAdder(20)

puts add4(6)    // 10
puts add20(2)   // 22

In this example, we have defined a function makeAdder with a single argument a, and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.

add4 and and20 are both closures. They share the same function body definition, but store different lexical environments. In the add4, x is 4, while in the add20, x is 20.

In the deep

// todo

Loop issue?

In JavaScript, we have var and let to declare variable.

Consider the following example:

We have array funcs to store functions. In the loop, we push a function which caputes the loop variable i and prints it out.

Let's call two functions:

Did it print 1 then 2 or 3 twice?

Now replace var with let and run them again.

Finally, we got what we expected.

In our language, the var keyword is same to JS's let. So in for-loop, the iterator variable is declared like what JS's let did.

To make the behavior becomes JS's var, you shoud put your iterator variable outside of loop:

Last updated

Was this helpful?