Skip to content

Instantly share code, notes, and snippets.

@bfatemi
Last active April 11, 2016 17:47
Show Gist options
  • Save bfatemi/16982f7eb4604fa39b55494721cd2b2d to your computer and use it in GitHub Desktop.
Save bfatemi/16982f7eb4604fa39b55494721cd2b2d to your computer and use it in GitHub Desktop.
Name masking - Preserving definition environment
j <- function(x) {
y <- 2 # Define y
# j returns this function
function() {
c(x, y)
}
}
k <- j(1)
k()
@bfatemi
Copy link
Author

bfatemi commented Apr 11, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment