VAL and VAL$

VAL x$ is like STR$ in reverse as it converts string x$ into the numeric representation of said string. For instance:

VAL "3.5"

returns 3.5. That is because if you take any number, apply STR$ to it, and then apply VAL to it, you will get back to the number you first thought of. That being said, if you take a string, apply VAL to it, and then apply STR$ to it, you do not always get back to your original string.

VAL is an extremely powerful function, because the string which is its argument is not restricted to looking like a plain number – it can be any numeric expression. Thus, for instance:

VAL "2*3"

will return 6 or even:

VAL ("2"+"*3")

will return the same. There are two things happening here. In the first, the argument of VAL is evaluated as a string: the string expression "2"+"*3" is evaluated to give the string "2*3". Then, the string has its double quotes stripped off, and what is left is evaluated as a number; so 2*3 is evaluated to give the number 6.

Now the following can get pretty confusing pretty fast if you do not pay the requisite attention: Remember that inside a string a string quote must be written twice. If you go down into further depths of strings, then you find that string quotes need to be quadrupled or even octupled.

There is another function, rather similar to VAL, called VAL$ x$. Its argument x$ is still a string, but its result is also a string. To see how this works, recall how VAL functions in two steps: first its argument is evaluated as a string, then the double quotes are stripped off this, and whatever is left is evaluated as a number. With VAL$, the first step is the same, but after the string quotes have been stripped off in the second step, whatever is left is evaluated as another string. Thus:

VAL$ """Fruit punch"""

equals to Fruit Punch (Notice how the string quotes proliferate again.) Do:

a$="99"

and print out all of the following: VAL a$, VAL "a$", VAL """a$""", VAL$ a$, VAL$ "a$" and VAL$ """a$""". Some of these will work, and some of them won't; try to explain all the answers (Try not to get overly confused).

Numeric functions

SGN

SGN x is the sign function (sometimes called signum). It is the first function you have seen that has nothing to do with strings, because both its argument x and its result are numbers. The result is +1 if the argument is positive, 0 if the argument is zero, and -1 if the argument is negative.


ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.