I'm writing a rock paper scissor game with Coffee Script and the code is not compiling as I'd expect.
CoffeeScript
if choice is opponent_choice then alert "Tie!"
Compiles to
if (choice === opponent_choice) alert("Tie!");
But I was expecting
if (choice === opponent_choice) {
alert("Tie!");
}
What do I need to change for this to compile in the way I expected?
I'm writing a rock paper scissor game with Coffee Script and the code is not compiling as I'd expect.
CoffeeScript
if choice is opponent_choice then alert "Tie!"
Compiles to
if (choice === opponent_choice) alert("Tie!");
But I was expecting
if (choice === opponent_choice) {
alert("Tie!");
}
What do I need to change for this to compile in the way I expected?
Share Improve this question asked Mar 9, 2012 at 23:53 Philip KirkbridePhilip Kirkbride 22.9k39 gold badges130 silver badges235 bronze badges 2- 4 Those two bits of code are equivalent. Why do you specifically need the latter and not the former? – ruakh Commented Mar 9, 2012 at 23:54
- 7 Why use coffee script as the source. If you want that much close control on the compiled javascript, why not just write javascript? – Billy Moon Commented Mar 9, 2012 at 23:57
4 Answers
Reset to default 15If there's only one statement on a line, you don't need the braces. They are functionally identical, and coffeescript compiler optimizing the output to use the least amount of characters.
Why does it matter?
For CS to create a block/multi-line then
you need to actually have a multi-line then
, like:
if choice is opponent_choice
alert "Tie!"
alert "Foo"
Which compiles to:
if (choice === opponent_choice) {
alert("Tie!");
alert("Foo");
}
Change your expectation, not the output.
Edit: add some details
CoffeeScript is a fine tool, not only a shorter way of writing code (which it is), but it re-formats many common patterns into good javascript. The output is often less readable than what you might have written yourself in javascript, but what it loses in clarity, it gains in improved programming patterns.
You should treat the CoffeeScript as the source, and not the compiled output. You would not dream of editing compiled output from other languages would you? (I know the analogy is a little bit of a stretch - but the point remains, source is for reading/writing and compiled output for executing).
// Generated by CoffeeScript 1.7.1
I use coffee of this version and can compile in the way you expected.
(function() {
if (choice === opponent_choice) {
alert("Tie!");
}
}).call(this);
You can have a try. However, I recommend you not to pay too much attention to the compiled output. It doesn't matter.