do.in.envir: Modify a function's scope

Description Usage Arguments Details Value Author(s) See Also Examples

Description

do.in.envir lets you write a function whose scope (enclosing environment) is defined at runtime, rather than by the environment in which it was defined.

Usage

1
2
3
4
5
# Use only as wrapper of function body, like this:
# my.fun <- function(...) do.in.envir( fbody, envir=)
# ... should be the arg list of "my.fun"
# fbody should be the code of "my.fun"
do.in.envir( fbody, envir=parent.frame(2)) # Don't use it like this!

Arguments

fbody

the code of the function, usually a braced expression

envir

the environment to become the function's enclosure

Details

By default, a do.in.envir function will have, as its enclosing environment, the environment in which it was called, rather than defined. It can therefore read variables in its caller's frame directly (i.e. without using get), and can assign to them via <<-. It's also possible to use do.in.envir to set a completely different enclosing environment; this is exemplified by some of the functions in debug, such as go.

Note the difference between do.in.envir and mlocal; mlocal functions evaluate in the frame of their caller (by default), whereas do.in.envir functions evaluate in their own frame, but have a non-standard enclosing environment defined by the envir argument.

Calls to e.g. sys.nframe won't work as expected inside do.in.envir functions. You need to offset the frame argument by 5, so that sys.parent() should be replaced by sys.parent( 5) and sys.call by sys.call(-5).

do.in.envir functions are awkward inside namespaced packages, because the code in fbody will have "forgotten" its original environment when it is eventually executed. This means that objects in the namespace will not be found.

The debug package does not yet trace inside do.in.envir functions– this will change.

Value

Whatever fbody returns.

Author(s)

Mark Bravington

See Also

mlocal

Examples

1
2
3
4
5
6
7
8
fff <- function( abcdef) ffdie( 3)
ffdie <- function( x) do.in.envir( { x+abcdef} )
fff( 9) # 12; ffdie wouldn't know about abcdef without the do.in.envir call
# Show sys.call issues
# Note that the "envir" argument in this case makes the
# "do.in.envir" call completely superfluous!
ffe <- function(...) do.in.envir( envir=sys.frame( sys.nframe()), sys.call( -5))
ffe( 27, b=4) # ffe( 27, b=4)

mvbutils documentation built on May 2, 2019, 8:32 a.m.