[R] on.exit() inside local()

Vadim Ogranovich vograno at evafunds.com
Tue Aug 10 02:07:40 CEST 2004


Since I routinely open files in a loop I've developed a habit of using
on.exit() to close them. Since on.exit() needs to be called within a
function I use eval() as a surrogate. For example:

for (fileName in c("a", "b")) eval({
	con <- file(fileName);

and con will be closed no matter what.

However it stopped working once I wrapped the loop in local():
> local(
+       for (foo in seq(2)) eval({
+         on.exit(cat(foo, "\n"))
+       })
+ )
Error in cat(foo, "\n") : Object "foo" not found

W/o local()it works just fine
>       for (foo in seq(2)) eval({
+         on.exit(cat(foo, "\n"))
+       })

The reason I wanted the local() is to keep 'foo' from interfering with
the existing environments, but somehow this breaks the thing.
At this point I am stuck. Could someone please tell what's going on?


More information about the R-help mailing list