我有一个函数open.account,它接受一个参数'total'并创建一个包含三个函数的列表(存款,取款,余额)。如果我运行test <- open.account(100)
,如何在不调用其中一个列表函数的情况下直接访问测试总值?
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")
}
)
}
答案 0 :(得分:2)
每个返回的函数都有自己的环境,其中存储了total
。
g <- open.account(total = 100)
environment(g$deposit)
# <environment: 0x279d0b0>
ls(environment(g$deposit))
# [1] "total"
environment(g$deposit)$total
# [1] 100