Skip to content

Instantly share code, notes, and snippets.

@moodymudskipper
Last active June 13, 2022 21:54
Show Gist options
  • Save moodymudskipper/bf8599cb5c539fb45b58d0c85f49c051 to your computer and use it in GitHub Desktop.
Save moodymudskipper/bf8599cb5c539fb45b58d0c85f49c051 to your computer and use it in GitHub Desktop.
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