Skip to content

Instantly share code, notes, and snippets.

@mfoos
Last active January 7, 2020 15:45
Show Gist options
  • Save mfoos/f1f953624c6f0a239286d708341f6b06 to your computer and use it in GitHub Desktop.
Save mfoos/f1f953624c6f0a239286d708341f6b06 to your computer and use it in GitHub Desktop.
Accessing private closure in R package
# Goal: To have a function that package users can call to set a variable that
# will be used to create a closure. The problem with the "problem" code
# is that it exposes the created function (private_function) to the user inappropriately.
############################ Problem
# a function in my package
user_calls <- function(string){
private_function <<- function(){
print(string)
}
}
# another function in my package
pkg_function <- function(){
private_function()
}
# user should be able to do
user_calls("kittens")
pkg_function()
# user should not be able to do
private_function()
############################ Solution
envex <- new.env()
user_calls <- function(string){
assign("private_function", function(){ print(string) }, envir = envex)
}
pkg_function <- function(){
envex$private_function()
}
user_calls("kittens")
pkg_function()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment