This question is similar to [Source script to separate environment in R, not the global environment](https://stackoverflow.com/questions/39620669/source-script-to-separate-environment-in-r-not-the-global-environment), but with a key twist.

Consider a script that sources another script:

```
# main.R
source("funs.R")
x <- 1

```

```
# funs.R
hello <- function() {message("Hi")}

```

I want to source the script `main.R` and keep everything in a "local" environment, say `env <- new.env()`. Normally, one could call `source("main.R", local = env)` and expect everything to be in the `env` environment. However, that's not the case here: **`x` is part of `env`, but the function `hello` is not! It is in `.GlobalEnv`.**

**Question: How can I source a script to a separate environment in R, even if that script itself sources other scripts, and without modifying the other scripts being sourced?**

Thanks for helping, and let me know if I can clarify anything.

EDIT 1: Updated question to be explicit that scripts being source cannot be modified (assume they are not under your control).