Skip to content

Instantly share code, notes, and snippets.

@moodymudskipper
Last active Jun 13, 2022
Embed
What would you like to do?
vassign
makeActiveBinding("v", local({
e <- NULL
count <- 1
function(value) {
# increment or reinitialize counter
exec_env <- sys.frame(-1)
if(identical(e, exec_env)) {
count <<- count + 1
} else {
count <<- 1
e <<- exec_env
}
# fetch function and body
call <- sys.call(-1)
caller_env <- sys.frame(-2)
f <- eval(call[[1]], caller_env)
calls <- as.list(body(f))[-1]
# assign
vpos <- which(sapply(calls, function(x) identical(x, quote(v))))
value <- eval(calls[vpos - 1][[count]], exec_env)
var <- as.character(calls[vpos + 1][count])
assign(var, value, exec_env)
}
}), .GlobalEnv)
test <- function() {
1
v
x
1 + 1
v
y
c(x, y)
}
test()
#> [1] 1 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment