# as_fquote() is meant to be called at every step of the way, so
# that each function can figure out a good default for `env`:
api_function <- function(expr, env = NULL) {
f <- as_fquote(expr, env)
expr_tool(f)
}
expr_tool <- function(expr, env = NULL) {
f <- as_fquote(expr, env)
# *** Do something useful with f ***
f
}
# Then the user can supply an expression or a formula. If an
# expression, and no environment is supplied, the caller
# environment is taken as default:
f <- api_function(quote(foobar))
env(f)
# The user can supply her own environment:
env <- new_env()
f <- api_function(quote(foobar), env)
identical(env(f), env)
# With a formula, the default is to take the formula environment
# rather than the caller environment:
my_f <- env_set(~expr, env)
f <- api_function(my_f)
identical(env(f), env)
# But the user can choose to provide her own environment as well:
f <- api_function(my_f, base_env())
identical(env(f), base_env())
Run the code above in your browser using DataLab