[R] on.exit() inside local()
Vadim Ogranovich
vograno at evafunds.com
Tue Aug 10 02:07:40 CEST 2004
Hi,
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);
on.exit(close(con))
})
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"))
+ })
1
2
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?
Thanks,
Vadim
More information about the R-help
mailing list