On Sat, Mar 19, 2011 at 8:02 PM, Russ Abbott <russ.abb...@gmail.com> wrote:
> Actually, I guess I'm not really talking about objects. I was looking
> through the scoping demo. It uses this function.
>
>> open.account <- function(total) {
>
> +
>
> +     list(
>
> +        deposit = function(amount) {
>
> +            if(amount <= 0)
>
> +                stop("Deposits must be positive!\n")
>
> +            total <<- total + amount
>
> +            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")
>
> +        }
>
> +        )
>
> + }
>
> I wanted to re-write the function so that instead of referring to total in
> deposit and withdraw I could refer to balance. Something like this,
>
> withdraw = function(amount) {
> +            if(amount > total)
> +                stop("You don't have that much money!\n")
> +            total <<- total - amount
> +            cat(amount,"withdrawn.  Your balance is", this,balance(),
> "\n\n")
>
> But that doesn't work. Is it possible to do this?
> Thanks.
>

Try this:

open.account <- function(total) {
    this <- environment()
    list(...same list as before...)
}

Now within the body of any of the methods in the list, this$total
refers to the balance.

-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to