Menu
CoddyTech

Environment Identity

Lesson 35 of 48 in Coddy's R for Luau Developers course.

Luau constructors can allocate new per-instance tables, while shared prototype fields or module state can intentionally share objects. R environments provide explicit reference-like state owners. Allocate one per independent owner instead of sharing one accidentally. Structural typing does not change the state lifetime or aliasing of either object representation.

Luau

local Counter={};Counter.__index=Counter;function Counter.new()return setmetatable({n=0},Counter)end;function Counter:add(n)self.n=self.n+n end;local a=Counter.new();local b=Counter.new();a:add(2);print(a.n..":"..b.n)

R

new_shelf <- function(){e<-new.env(parent=emptyenv());e$books<-character(0);e}
a<-new_shelf();b<-new_shelf();a$books<-c(a$books,"tea")
cat(length(b$books),"\n",sep="")

An aliased environment remains shared by reference.

challenge icon

Challenge

Easy

Implement new_counter() returning an environment with value zero, and advance(counter,amount) adding amount to its value and returning the new value. For all input numbers, call advance on one counter and return its final value. Empty input returns zero.

Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.

Your code goes in Counter.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.

Try it yourself

source("Counter.R")
source("Exercise.R")
a<-new_counter();b<-new_counter();alias<-a;stopifnot(is.environment(a));invisible(advance(a,6));stopifnot(identical(alias$value,6),identical(b$value,0))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for Luau Developers

Practice on your own: Online R compiler