-
Notifications
You must be signed in to change notification settings - Fork 8
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Replace .validLHS() with tryCatch()? #88
Comments
Alternatively, we could create a function that executes the pattern: assign_in_place <- function(x, val = x){
xn <- substitute(x)
xnn <- eval.parent(call("substitute", xn))
eval.parent(on.exit(tryCatch(
eval.parent(call("<-", xnn, val), n = 2),
error = identity
)))
invisible(val)
} Then, a function can call it as the last thing and modify its argument in place: f <- function(x){
assign_in_place(x, x+1)
}
y <- 1
z <- 1
(f(z)) # Changed
#> [1] 2
z # Changed
#> [1] 2
(f(y)) # Changed
#> [1] 2
y # Changed
#> [1] 2
(f(z)) # Changed
#> [1] 3
z # Changed
#> [1] 3
(f(identity(z))) # Changed
#> [1] 4
z # Unchanged
#> [1] 3 Created on 2024-11-14 with reprex v2.1.1 |
A slightly more sophisticated version, that is robust to modify_in_place <- function(x, value = x){
xn <- substitute(x) # Grab the name of the argument to be updated.
xnn <- match.call(sys.function(-1), sys.call(-1))[[xn]] # Grab the expression that was passed into its argument.
eval.parent(on.exit( # As the calling function exits...
tryCatch( # try to...
eval.parent(call("<-", xnn, value), n = 2), # Assign to the expression in the caller's calling environment the expression,
error = identity # and do nothing if it fails.
)))
invisible(value) # Return invisibly.
} @CarterButts , thoughts? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The ultimate test of whether something can be assigned to is to actually try assigning to it.
It may therefore make sense to replace the
pattern with the much simpler
or, since we don't care about the
try-error
object,Thoughts? @CarterButts ?
The text was updated successfully, but these errors were encountered: