Hi,

I'm working on a presentation regarding the modification of the
function body on-the-fly and just discovered something I don't
understand. I would like to modify a body of the function within a
function, but I see that it is possible only when explicitly referring
to the environment where the function is defined:

fun1 <- function() {
  1
  body(fun1)[[2]] <- "one"
}
fun1()
body(fun1)
#> {
#>     1
#>     body(fun1)[[2]] <- "one"
#> }

fun2 <- function() {
  2
  env <- environment(fun2)
  body(env$fun2)[[2]] <- "two"
}
fun2()
body(fun2)
#> {
#>     "two"
#>     env <- environment(fun2)
#>     body(env$fun2)[[2]] <- "two"
#> }

Can I get some explanation or some links / articles about this,
please? I thought it won't be a difference and I should be able to
modify a function body also in the first case, because I'm changing
something in the parent environment being in the child environment.

Best regards,

Grzegorz

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to