# Create a function with a given environment:
env <- new_env(base_env())
fn <- with_env(env, function() NULL)
identical(env(fn), env)
# env_set() does not work by side effect. Setting a new environment
# for fn has no effect on the original function:
other_env <- new_env()
env_set(fn, other_env)
identical(env(fn), other_env)
# env_set() returns a new function with a different environment, so
# you need to assign the returned function to the `fn` name:
fn <- env_set(fn, other_env)
identical(env(fn), other_env)
Run the code above in your browser using DataLab