Is this a bug or a feature - define function in for express.

35 views
Skip to first unread message

linjie nie

unread,
Jul 23, 2013, 3:21:42 AM7/23/13
to lives...@googlegroups.com
Hi, All -
Is this a bug or a feature? 

fn={}
for x in [1,2,3]
  fn[x] = -> it + x

fn[1](1) == 2 # but is 6


George Zahariev

unread,
Jul 23, 2013, 4:30:47 AM7/23/13
to lives...@googlegroups.com
I know this can be a bit confusing, but it makes a lot of sense. I think that fact that it is happening in a loop is throwing you off.

Look at this code:

x = 1
f
= -> it + x
console
.log f 1
x
= 100
console
.log f 1


What is printed to the console?
Is the value of x in the function "f" evaluated when the function is defined, or when it is called?
The answer is when it is run. This will print to the console:

2
101


If you look at the loop again, you will see when you call the function, the value of x is its value in the last iteration of the loop, that is to say, "3"
Thus all the functions you create are the same, all of them add their argument to "3".

If you want to do what you are thinking off, you must do:

fn={}
for x in [1,2,3]

  let
    fn
[x] = -> it + x


fn
[1](1)


Which in the next version of LiveScript will simply be, "for let ...."

This works because you are wrapping the body of the loop with "let", which is like wrapping it in an anonymous function and calling it with "x", so that the "x" in the function you are creating no longer refers to the mutating variable in the loop, but the parameter of the wrapping function ("let") which was just called with the current value of "x" in the loop. 

linjie nie

unread,
Jul 30, 2013, 10:36:50 AM7/30/13
to lives...@googlegroups.com
I see, thank you very much.
Reply all
Reply to author
Forward
0 new messages