-
-
Save klmr/53c9400e832d7fd9ea5c to your computer and use it in GitHub Desktop.
Example code illustrating why `local` doesn’t help.
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
# 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 |
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 = function () { | |
message(get_meta()) | |
# Load something | |
load_helper('user_provided_helper.r') | |
# So that this function can use some helpers: | |
helper() | |
message(get_meta()) | |
} |
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
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