I am trying to create a decorator in R that when used inside of another function will use the calling environment of that function as parent. I believe this can be achieved using eval() but I am having difficulties with the implementation.
This is what I got so far:
library(rlang)
###Decorator definition
dynamicCall <- function(decorated) {
dynamicEnv <- new.env(parent = parent.frame())
attach(dynamicEnv)
eval(decorated, enclos = dynamicEnv)
print('parents in dynamicCall')
print(env_parents(dynamicEnv))
}
###Function to be decorated
f <- function() {
print('parents in f')
print(env_parents(environment()))
}
###Function to be called in
g <- function() {
print('calling environment')
print(environment())
dynamicCall(f())
}
g()
And this is the output:
[1] "calling environment"
<environment: 0x00000211a91ff840>
[1] "parents in f"
[[1]] $ <env: global>
[1] "parents in dynamicCall"
[[1]] <env: 0x00000211a91ff840>
[[2]] $ <env: global>
I don't understand why "parents in f" is different than "parents in dynamicCall". The enclosing environment should be dynamicEnv so the parents list should be the same? I'll be grateful for any help!
edit: adding the library