suve

awful: tutorial: input

While writing scripts sure is fun, it would be useful to also make running them fun. One of the ways to achieve this is, of course, to interact with the user. This section of the tutorial will focus on handling user input in awful.

Reading values

:set &NAME s""
:set &AGE i0
:write s"What is your name? "
:read &NAME
:write s"What is your age? "
:read &AGE
:writeln s'Hello, ' $NAME s'. It was interesting to meet a ' $AGE s'-year-old.'

The snippet above asks the user for this name and age and reads them from standard input. As you probably noticed, reading values is done using the :read function. It can take any number of parameters, and then reads them from standard input in left-to-right order. When a user inputs data, spaces (or newlines) are treated as value separators. How data will be interpreted depends on the type of variable we read into - e.g. because AGE is an int, if the user wrote his name twice, the awful interpreter would try to convert the name into some numeric value. Which would probably yield zero, since names usually do not have digits in them.

Concerning strings

:set &ONE &TWO s''
:writeln s'Tell me your first and last name.'
:read &ONE
:writeln s'Sorry, could you repeat?'
:stdin-clear
:readln &TWO
:writeln s'ONE: ' $ONE
:writeln s'TWO: ' $TWO

It was said in the previous paragraph that spaces are treated as value separators. But what if we want to read multiple words into a string? This is where the :readln function comes into play. It differs from the standard :read function, as it accepts only one value per line. This means that, while it is possible for the user to write several numbers as one line of input, and :read will happily assign them to variables passed, :readln will expect each number to appear on a separate line. This behaviour can be used to read entire lines into strings, as there will be no breaking at spaces.

Note the use of the :stdin-clear function. When we perform the first :read call, only the first part of the input is put into the variable, and the rest is kept in buffer. Readlining without clearing the input buffer would result in TWO being assigned the leftover input left in buffer after the previous reading. Clearing the input makes sure the buffer is empty, and the user must provide a fresh, new, tasty value for us.


Next: ⇒ Arithmetic ⇒
Back: ⇐ Variables ⇐

wikistrona zmodyfikowana 2014/0601/2317