Last active
June 13, 2022 21:54
-
-
Save moodymudskipper/bf8599cb5c539fb45b58d0c85f49c051 to your computer and use it in GitHub Desktop.
vassign
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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