Skip to content

Instantly share code, notes, and snippets.

@klmr
Created December 11, 2015 12:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save klmr/53c9400e832d7fd9ea5c to your computer and use it in GitHub Desktop.
Save klmr/53c9400e832d7fd9ea5c to your computer and use it in GitHub Desktop.
Example code illustrating why `local` doesn’t help.
# Package code
get_meta = function () get('.meta', parent.frame(), inherits = TRUE)
load_helper = function (helper_file) {
caller = parent.frame()
e = new.env(parent = parent.env(caller))
e$.meta = 'helper'
eval(parse(helper_file), envir = e)
parent.env(caller) = e
}
# Usage:
env = new.env()
env$.meta = 'original'
eval(parse('user_provided_code.r'), envir = env)
env$f()
## original
## This is a helpful helper
## helper
f = function () {
message(get_meta())
# Load something
load_helper('user_provided_helper.r')
# So that this function can use some helpers:
helper()
message(get_meta())
}
helper = function () message("This is a helpful helper")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment