3.8
Await and defer have a subtle relationship with function calls, so before putting await inside a user-
defined function, find understand the Web pages about “Iced CofeeScript” (if using await inside a
function, that function should also return its results using callbacks).
However, await is very straightforward and useful when used together with loops. Here is an example:
await readnum 'How many numbers to average?', defer count
total = 0
for j in [1..count]
await readnum 'Enter #' + j, defer val
total += val
write 'The total is ' + total
write 'The average is ' + (total / count)
This style of code is called “blocking i/o”, because the program blocks (stops) its progress while waiting
for an input or output to occur. Blocking i/o is the traditional way to teach Python or C input/output, but it is
very different from the way UI events are typically handled in JavaScript or Java GUIs, where input is
done using event handlers. Iced CoffeeScript’s await allows teaching both styles in the same system,
and even in the same program.
The await keyword is so useful that a version of it is on track to be added to a future version of the
JavaScript standard. However, it is not in the language right now, so you cannot use await in JavaScript
today. Instead, you must use function definitions (see Chapter 5) to achieve similar effects.
Polling Keyboard State Using pressed
So far we have seen two styles of input: “event handling”, and “blocking i/o.” A third style of input, called
polling, is often used in video games and real-time systems such as robots and you can also try it with
Pencil Code. A program using polling repeatedly checks the input state (of the keyboard) by asking a
question such as “is the key pressed down right now?”
Here is how Pencil Code does polling (usually in combination with the “forever” command).
forever ->
if pressed 'W'
fd 2
if pressed 'D'
rt 2
Inside a forever block, the function pressed
can be used to poll the keyboard state.
The “pressed” command is the polling command. It is true if a key is pressed and it is false if the key is
not pressed. The “if” can be used decide whether to take an action based on the state of a key. With
“pressed,” it is even possible to support “chording”, that is, making a program that responds to two keys
pressed at the same time. Students can experiment with this effect in the program above.
Polling is an advanced technique and there are several subtleties for getting it to work correctly that are
handled by the “forever” command. A “forever” loop differs from a traditional loop in several ways.
Inside a “forever” loop, the speed of turtles is automatically set to Infinity to avoid animation delays. Also,
a “forever” loop will also automatically put a short delay between each repetition so that you can see the
effects of the repetition over time. You can change the framerate of the “forever” loop by adding an extra
number argument. For example, “forever 10” will do 10 frames per second.