Created
July 23, 2011 12:02
-
-
Save vlasovskikh/1101352 to your computer and use it in GitHub Desktop.
Local vars in CoffeeScript are nonlocal sometimes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
f = -> | |
x = 2 | |
x = 1 | |
> console.debug "x = #{ x }" | |
x = 1 | |
> console.debug "f() = #{ f() }" | |
f() = 2 | |
> console.debug "x = #{ x }" | |
x = 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x = 1 | |
f = -> | |
x = 2 | |
> console.debug "x = #{ x }" | |
x = 1 | |
> console.debug "f() = #{ f() }" | |
f() = 2 | |
> console.debug "x = #{ x }" | |
x = 2 |
@autotelicum Yep, I'm aware of the scoping rules in CoffeScript, but they are a little bit weird from a pythonista's perspective. Thanks for the pointer to your book!
Then this might be more relevant:
http://blog.ssokolow.com/archives/2011/05/07/a-python-programmers-first-impression-of-coffeescript/
If you are interested in the pro/contra of scoping: jashkenas/coffeescript#1121
@autotelicum Thanks for these very relevant links! :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From Smooth CoffeeScript p 49... (or p 51... with solutions):
When looking up a variable inside a function, the outer environment is checked first, and only if the variable does not exist there is it created in the local environment.
...
So if the name of variable in an inner function exists in an outer environment then the variable is referring to the outer one, it is not a new definition. That is an expression like variable = 'something' may be a definition of a new variable or it may be an assignment to a previously defined variable. As a matter of style, when you are using top-level variables then it makes sense to introduce them at the top of a file with a default value.
...
The easiest way to deal with variables is to use unique names for variables throughout a file.
...
There is also a diagram and a handful of examples.