small medium large xlarge

Back to: All Forums  CoffeeScript
Generic-user-small
05 Nov 2011, 00:59
Pawel Osiczko (2 posts)

Ok, so what’s the story with coffeescript REPL? I expected variable age to be defined with global scope and it behaves as it isn’t:

18:49:19 pablo@galileo [~]> node -v
v0.5.10
18:49:22 pablo@galileo [~]> coffee -v
CoffeeScript version 1.1.3-pre
18:49:54 pablo@galileo [~]> coffee
coffee> age = 99
99
coffee> reincarnate = -> age = 0
[Function]
coffee> reincarnate()
0
coffee> console.log "I am #{age} years old"
I am 99 years old
coffee> 

When running the same code through non-interactive session, I get correct behavior.

18:53:28 pablo@galileo [~]> cat a.coffee 
age = 99
reincarnate = -> age = 0
reincarnate()
console.log "I am #{age} years old"
18:53:32 pablo@galileo [~]> coffee a.coffee 
I am 0 years old
18:55:15 pablo@galileo [~]> coffee -cbp a.coffee 
var age, reincarnate;

age = 99;

reincarnate = function() {
  return age = 0;
};

reincarnate();

console.log("I am " + age + " years old");

What am I missing?

Thanks for your help!

–p

Trevor_burnham__goofy_headshot__pragsmall
05 Nov 2011, 18:02
Trevor Burnham (54 posts)

Don’t worry, you’re not missing anything! I just opened a new issue on this: https://github.com/jashkenas/coffee-script/issues/1829

The problem is that the REPL compiles each line independently. The only thing that’s shared from one line to another is global variables. Writing @age = 99@ on the REPL creates a global, but the CoffeeScript compiler ignores globals when deciding whether a variable should be scoped in a function or not. Make sense?

Notice that if you enter @age = 99; reincarnate = -> age = 0; reincarnate(); console.log “I am #{age} years old”;@ as one line on the REPL, you’ll get the same behavior as you do when running that code from a .coffee file.

In conclusion: The REPL is your friend… but a text editor with a “Run” command is an even better one.

Codelahoma_pragsmall
02 Jan 2012, 01:12
Rod Knowlton (1 post)

And somewhere in-between the text editor and the REPL is the (undocumented) REPL continuation character:

coffee> age = 99\
......> reincarnate = -> age = 0\
......> reincarnate()\
......> console.log "I am #{age} years old"
I am 0 years old
You must be logged in to comment