Reputation: 89
I have a function open.account which takes an argument 'total' and creates a list of three functions (deposit, withdraw, balance). If I run test <- open.account(100)
how can I access the value of total for test directly without calling one of the list functions?
open.account <- function(total) {
list(
deposit = function(amount) {
if(amount <= 0)
stop("Deposits must be positive!\n")
total <<- total + amountw
cat(amount, "deposited. Your balance is", total, "\n\n")
},
withdraw = function(amount) {
if(amount > total)
stop("You don't have that much money!\n")
total <<- total - amount
cat(amount, "withdrawn. Your balance is", total, "\n\n")
},
balance = function() {
cat("Your balance is", total, "\n\n")
}
)
}
Upvotes: 0
Views: 41
Reputation: 25736
Each returned function has its own environment where total
is stored.
g <- open.account(total = 100)
environment(g$deposit)
# <environment: 0x279d0b0>
ls(environment(g$deposit))
# [1] "total"
environment(g$deposit)$total
# [1] 100
Upvotes: 2