Hi,
in my project I want the user to be able to write hook functions that
are in turn called in my main code. I'd like the user's hooks to be able
to call some function that set a variable outside their running
environment. The trick is that this variable is not global, but defined
on runtime before calling the hooks, and I don't want to leave any trace
(i.e. global variables) after the main code has finished.
I thought that the following would work but it doesn't. I guess I got
too messy with environment and enclosures:
# global function defined by the user
fun.global <- function(){
message('fun.global')
setVar(5) #
}
# my main code
main <- function(){
message('main')
# define a function to set some local variable
setVar <- local({
l.var <- 0
function(value){
message('setVar')
l.var <<- value
}
})
.workspace <- environment(setVar)
environment(setVar) <- new.env()
eval(fun.global(), enclos=environment(setVar))
print(get('l.var', envir=.workspace, inherits=FALSE))
}
main()
I get the following output:
> main
> fun.global
> Error in fun.global() : could not find function "setVar"
There is definitely a problem of lookup somewhere. I first tried without
eval, as I thought that function setVar would then be defined in a
parent environment of the call to fun.global, but it does not work either.
Can anybody tell me what's the problem and how I should do my stuff?
Thanks,
Renaud
______________________________________________
R-help@r-project.org mailing list
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.