eval_closure: Eval code in closure without scoping problems (memory leaks)

View source: R/funky.R

eval_closureR Documentation

Eval code in closure without scoping problems (memory leaks)

Description

Evaluate an expression inside of closure that has an optimal scope. This is very important, if your closure does return a function, since the the entire environment tree (including the entire ancestry) is kept in memory as long as your function is present. This is a common cause for memory leaks. With eval_closure() you can assign an environment that contains only the needed variables (copies) and an optimal scope ancestry can be defined by parent_env. Be sure, to choose the right environment for parent_env!

Usage

eval_closure(
  expr,
  vars = NULL,
  lookup_env = parent.frame(),
  parent_env = .GlobalEnv
)

Arguments

expr

The expression, which should be evaluated inside of the closure.

vars

An optional object, telling which variables should be available inside the closure. It can either be

  • a character vector holding the names of the variables which should looked up in the environment lookup_env.

  • a named list: In this case, the values are not looked up in lookup_env, but directly taken from the list item values and the list item names are used as variable names.

lookup_env

The environment holding the variables for which the names are defined in the character vector vars. If vars is a list or NULL, then lookup_env is not used. The default for lookup_env is the environment where the function fn was defined.

parent_env

The parent environment (either an environment or a string holding the name of an R package whoose namespace should be used as parent environment), which should be assigned to the closure. This argument is very important, since it determines which objects will be available inside of your closure. Usually one of the following two possibilities is the right choice for parent_env:

  • parent_env = .GlobalEnv (default): The global environment is usually the right choice for an expression, which does not use any non-exported functions or any imported functions of any R package. This is usually the case, when the closure is created outside of any R package (e.g. not inside of a function that is part of an R package).

  • parent_env = "MY_PKG": This is usually the right choice when you are developing a new R package and want to create a closure inside of another function of this package (in this example the package name is MY_PKG). This ensures that also non-exported functions and imported functions of MY_PKG are available inside of your closure as well as the global environment.


R-package/styledTables documentation built on Feb. 6, 2024, 2:21 a.m.