[R] Scope and assignment: baffling

Jeff Brown dopethatwantscash at yahoo.com
Thu Apr 1 03:44:34 CEST 2010


Hi,

The code below creates a value, x$a, which depending on how you access it
evaluates to its initial value, or to what it's been changed to.  The last
two lines should, I would have thought, evaluate to the same value, but they
don't.

f <- function () {
	x <- NULL;
	x$a <- 0;
	x$get.a <- function () {
		x$a;
	};
	x$increment.a <- function () {
		x$a <<- x$a + 5;
	};
	x
};
x <- f();
x$increment.a();
x$get.a();
x$a;

This can be repeated; each time you call x$increment.a(), the value
displayed by x$get.a() changes, but x$a continues to be zero.

Is that totally weird, or what?

Thanks,
Jeff
-- 
View this message in context: http://n4.nabble.com/Scope-and-assignment-baffling-tp1747582p1747582.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list