Set a functions environment to that of the calling environment (parent.frame) from within function

旧城冷巷雨未停 提交于 2019-11-28 08:27:41
MrFlick

Well, a function cannot change it's default environment, but you can use eval to run code in a different environment. I'm not sure this exactly qualifies as elegant, but this should work:

helpFunction<-function(){
    eval(quote(importantVar1+1), parent.frame())
}

mainFunction<-function(importantVar1){
    return(helpFunction())
}

mainFunction(importantVar1=3)

If you declare each of your functions to be used with dynamic scoping at the beginning of mainfunction as shown in the example below it will work. Using helpFunction defined in the question:

mainfunction <- function(importantVar1) {

    # declare each of your functions to be used with dynamic scoping like this:
    environment(helpFunction) <- environment()

    helpFunction()
}

mainfunction(importantVar1=3)

The source of the helper functions themselves does not need to be modified.

By the way you might want to look into Reference Classes or the proto package since it seems as if you are trying to do object oriented programming through the back door.

The R way would be passing function arguments:

helpFunction<-function(x){ 
#you can also use importantVar1 as argument name instead of x
#it will be local to this helper function, but since you pass the value
#it will have the same value as in the main function
  x+1
}

mainFunction<-function(importantVar1){
  helpFunction(importantVar1)
}

mainFunction(importantVar1=3)
#[1] 4

Edit since you claim it "doesn't work":

helpFunction<-function(importantVar1){ 
  importantVar1+1
}

mainFunction<-function(importantVar1){
  helpFunction(importantVar1)
}

mainFunction(importantVar1=3)
#[1] 4
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!