jashkenas/coffee-script — Issue #1829: Variable scope in functions defined in the REPL
Author: TrevorBurnham
Created: 2011-11-05 17:56:55+00:00
State: open

A helpful reader of my book [posted a good question](http://forums.pragprog.com/forums/169/topics/9901). Here's his issue:

coffee> foo = 1
1
coffee> do -> foo = 2
2
coffee> foo
1

This isn't a new issue; it's been ever thus, and it's obvious why it's happening. But I don't think it's ideal. So I put together [a small fix](https://github.com/TrevorBurnham/coffee-script/commit/1e781e624bf4684fd5a2d39bc3fd20358d52ba4f), which moves all globals into the local scope before evaluating the input.

But there is a tradeoff here, as the patch produces this behavior:

coffee> global.bar = 1
1
coffee> do -> console.log bar = 2 * Math.PI
6.283185307179586
coffee> global.bar
6.283185307179586

That strikes me as a smaller problem, but it'd be nice if both cases could be made to have the same scoping behavior as when you run the same code in a .coffee file.