6.7 Closures

R RUNTIMESTATUS: STABLELEVEL: INTERMEDIATEREVIEWED: 2026-11-18
Before this page Environments

6.7.1 Motivation

Every function you define in R is a closure. The runtime does not store your function as code alone. It stores code plus a live reference to the environment where the function was created. That one design choice explains function factories, the classic loop-capture bug, surprise memory retention, and slow worker startup in parallel code.

The word “closure” comes from the idea that the function “closes over” the variables around it. The function carries its birthplace with it, wherever it travels.

6.7.2 Mental model

Think of an R function as a set of three parts, stapled together:

  1. Formals. The argument list, with any default expressions.
  2. Body. The unevaluated code, stored as an AST.
  3. Environment. A pointer to the environment where function(...) was evaluated.

The third part is the important one. It is a pointer, not a copy. When R evaluates the function later, it creates a fresh frame for the arguments. It sets the parent of that frame to the captured environment. Every free variable in the body resolves through that chain. The details of the chain live on the environments page.

A useful analogy: the function is a letter, and the environment is the return address printed on it. The letter can travel far, but lookups always route back to the return address. The analogy ends there, because the return address here is a live, mutable object.

6.7.3 Mechanism

The three accessors

R exposes each part of a closure directly:

f <- function(x, n = 2) x^n

formals(f)
#> $x
#>
#> $n
#> [1] 2

body(f)
#> x^n

environment(f)
#> <environment: R_GlobalEnv>

All three have replacement forms. body(f) <- quote(x + n) rewrites the code. environment(f) <- new.env() reseats the function in a different scope. This is legal, ordinary R. A package function has its package namespace as its environment for a plainer reason: R evaluates the package’s R code inside the namespace when it installs the package, so every function(...) there captures the namespace.

Not every callable object is a closure. sum and if are primitives. They live as BUILTINSXP and SPECIALSXP nodes that hold an index into R’s table of C functions (R_FunTab) inside the interpreter. typeof shows the difference:

typeof(function(x) x)   # "closure"
typeof(sum)             # "builtin"
typeof(`if`)            # "special"

The CLOSXP node

Inside the runtime, a closure is one heap node of type CLOSXP. Like every R object, it is a SEXP with a standard header. Its payload is three pointers. Inside R the macros FORMALS, BODY, and CLOENV read them. R 4.5.0 added public API functions for packages, and in R 4.6.1 the installed header no longer declares the old names:

/* R 4.6.1 public API, from Rinternals.h */
SEXP formals = R_ClosureFormals(fn);  /* pairlist of arguments and defaults */
SEXP body    = R_ClosureBody(fn);     /* language object, the AST           */
SEXP env     = R_ClosureEnv(fn);      /* the enclosing environment          */

The node holds no machine code and no copies of captured values. It holds three pointers into the heap. Two closures created in the same scope share one environment object. That sharing is the source of everything else on this page. The general layout of heap nodes is on the R objects page and the SEXP page.

6.7.4 A simple example

The classic demonstration is a counter factory:

make_counter <- function() {
  count <- 0
  function() {
    count <<- count + 1
    count
  }
}

c1 <- make_counter()
c2 <- make_counter()
c1()  # 1
c1()  # 2
c2()  # 1

Each call to make_counter creates a fresh execution frame. That frame holds count. The inner function() captures that frame as its CLOENV. The frame does not die when make_counter returns, because the returned closure still points at it. c1 and c2 point at two different frames, so the counters do not interfere.

flowchart TD
  c1["c1: CLOSXP"] --> fo("formals: none")
  c1 --> bo("body: { count &lt;&lt;-<br/>count + 1; count }")
  c1 --> env["frame of make_counter<br/>count = 2"]
  env --> ge["global environment"]
  ge --> pk["package environments"]
  pk --> be["base environment"]

A closure node points at formals, body, and one environment, and that environment chains upward to base.

The <<- operator walks the same chain. It finds the binding for count in the captured frame and rewrites it in place. This is why the counter has state: the closure mutates the environment it closed over.

6.7.5 Capture is by reference

R does not copy captured variables into the closure. The closure holds a reference to a shared, mutable environment. Two consequences follow, and both surprise people.

Closure structure and environment chain

c1 formals, body, environment c2 formals, body, environment frame of the first call count = 2 frame of the second call count = 1 enclosing environment global environment then the package environments and base

Each call to make_counter makes a new frame, and each returned closure keeps a reference to its own frame, so c1 and c2 count separately.

The loop pitfall

Build three functions in a for loop:

adders <- list()
for (i in 1:3) {
  adders[[i]] <- function(x) x + i
}
adders[[1]](10)  # 13, not 11
adders[[2]](10)  # 13
adders[[3]](10)  # 13

All three closures were created in the same environment, the global one. All three store the same CLOENV pointer. None of them stores a private copy of i. When any of them runs, it looks up i in the shared environment and finds the value the loop left behind: 3.

The fix is to give each closure a private environment. A function factory does this, because each call creates a fresh frame:

make_adder <- function(n) {
  force(n)
  function(x) x + n
}
adders <- lapply(1:3, make_adder)
adders[[1]](10)  # 11

The reason for force(n)

The factory alone is not always enough, because arguments in R are lazy. n arrives as a promise: an unevaluated expression plus the environment to evaluate it in. If nothing reads n before the factory returns, the promise stays unevaluated. When a closure finally forces it, the promise evaluates its expression in the caller’s environment, and that environment can have moved on.

force(n) is nothing special. It reads n, which forces the promise now and pins the current value into the frame. Since R 3.2.0, lapply and its relatives force the first argument of each call to FUN for you (internally through R_forceAndCall), which is why the factory above gives 11 even without the force. Hand-rolled higher-order functions do not get this help, so the explicit force habit remains correct. The full mechanics live on the promises and lazy evaluation page.

Default arguments are also promises, with one difference. A default expression evaluates in the function’s own execution frame, not in the caller. That is why a default like n = length(x) can see the other arguments.

6.7.6 The hard part

A small closure can pin a large object

R captures the whole environment, not the variables the body mentions. The runtime does not analyze the body to compute a minimal capture set. It cannot do this safely, because eval, get, <<-, and sys.function let a body reach any binding in scope at runtime. Whole-environment capture is the safe choice for a language this dynamic.

The memory consequence is real:

summarize <- function(path) {
  big <- read.csv(path)        # say 2 GB in memory
  n   <- nrow(big)
  function() n                 # uses only n
}

f <- summarize("huge.csv")

The returned closure uses only n. But its CLOENV is the whole frame of summarize, and that frame binds big. The garbage collector reaches the frame through the closure’s CLOENV, reaches big through the frame, and keeps all 2 GB alive. The closure looks tiny, but what it keeps alive is not.

A live closure keeps its entire enclosing environment chain reachable. The GC cannot free any binding in that chain, used or not, for as long as the binding exists and the closure is alive.

Two idioms release the memory. Drop the binding before you return, or return a closure with a hand-built minimal environment:

summarize <- function(path) {
  big <- read.csv(path)
  n   <- nrow(big)
  rm(big)                      # frame no longer binds the data
  function() n
}

Serialization drags the chain

The same retention problem crosses process boundaries. When you serialize a closure, R writes the formals, the body, and the environment, and then it recurses into the environment’s own bindings and parent. The serialization format stops at the global, base and empty environments, at namespaces, and at attached package environments, which it writes as references by name or by type. Everything below that line travels in full.

So a closure born inside a function drags every frame between itself and the global environment, with all their bindings. This is why a parallel task that sends “one small function” to a worker sometimes ships gigabytes. The worker deserializes the whole chain, and the parent references resolve to the worker’s own global environment and namespaces.

6.7.7 Other languages

Rust makes capture explicit and checks it at compile time. A Rust closure captures each variable its body uses, one by one. It picks the weakest mode that works: shared borrow, mutable borrow, or move. The move keyword forces capture by value:

let n = big_table.len();
let f = move |x: usize| x + n;   // n is copied into the closure
// big_table is untouched. Only n moved, and n is Copy.

The compiler computes the capture set from the closure body. It rejects a closure that outlives a borrowed variable. The loop pitfall from above does not compile in Rust unless each iteration moves or copies its own value. The price is the ownership discipline: the programmer must satisfy the borrow checker before the program runs.

Python sits closer to R. A Python closure captures variables by reference through cell objects, and the same loop bug appears with lambda: i in a for loop. Python differs in granularity: it captures individual variables, not whole scopes, because Python resolves the capture set statically at compile time.

R chose maximal dynamism, so it must capture maximally. Rust chose static checking, so it can capture minimally and prove the result safe before the program runs.

6.7.8 Relevance to my work

Closures are the reason “just send the function to another thread” is not a plan in R. A closure is a handle on a mutable environment chain that runs through the global and base environments, which the whole session shares. The why R is difficult to parallelize page develops this at length.

In GNU R and in threaded-r, the environment chain of an ordinary closure passes through the base environment before it reaches the empty environment. threaded-r gives each interpreter its own symbol table, and so its own base bindings, which gives each interpreter’s closures a private end of the chain. The exception is 38 symbols that compiled packages reach through exported globals: they stay one object each, and each interpreter keeps their bindings in a small record of its own.

sunlight runs tasks in workers forked from a template process, not from the user’s session, so a task closure cannot rely on the caller’s environment. At spawn time, in the parent, sunlight checks the task function’s free symbols and refuses one that names anything outside its own arguments, base R, and the pool’s preloaded packages. The explicit inputs are forced and snapshotted at that moment, so later changes in the parent cannot leak into the task, and the shipped payload stays explicit.

rrs represents a closure as formals, a body, and an environment handle, all on the heap of one interpreter, and each interpreter owns its heap, GC, and symbol table. A handle is an index into one heap and means nothing in another. The type system does not enforce that yet, and a test-time verifier catches a stray handle only when it lands on a freed slot. There is no global mutable state for a capture to reach.

threaded-r gives each interpreter its own heap. What happens to a closure whose environment chain a package captured before the interpreter was created? An immortal arena covers the builtin constants today, but a closure is not a constant.

Further reading

Where this appears

  • threaded-r Closure environments chain into the base environment, the exact place where threaded-r split SYMVALUE per interpreter.
  • r-in-rust (rrs) rrs must represent every user function as code plus an environment handle on a per-interpreter heap.
  • sunlight A task closure decides what a forked worker sees, so sunlight checks capture at spawn time.

Where to go next

Back to top