Last active
April 11, 2016 17:47
-
-
Save bfatemi/16982f7eb4604fa39b55494721cd2b2d to your computer and use it in GitHub Desktop.
Name masking - Preserving definition environment
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
j <- function(x) { | |
y <- 2 # Define y | |
# j returns this function | |
function() { | |
c(x, y) | |
} | |
} | |
k <- j(1) | |
k() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Name Masking
Lexical scoping looks up symbol values based on how functions were nested when they were created, not how they are nested when they are called. With lexical scoping, you don’t need to know how the function is called to figure out where the value of a variable will be looked up. You just need to look at the function’s definition.
Example
This example illustrates a basic principle of lexical scoping. This works because k preserves the environment in which it was defined and because the environment includes the value of y.