I need to load a custom function from an extern file but without causing side-effects.
Currently, I’m doing in this way:
src <- "function(x,y) { return(x + y) }"
# parse the source
ptree <- parse(text=src)
# execute the evaluation using a data.frame as environment (like a sandbox)
f <- eval(ptree, envir=data.frame())
if(!is.function(f))
stop('The given source does not contain a valid function')
f(1,1)
In this way, a “malicious” code does not affect the current environment, e.g. :
src <- "a <- 1"
so, an existing "a" variable will not be changed by the eval function.
Do you see any drawbacks in this ?
Are there better ways ?
Thanks in advance
You can store your function in a custom environment. You can access it by specifying the environment.