|
More Formatting of Strings with F$() |
f$()
Most of the text a program builds is a sentence with values in it: a
message to a user, a line in a log, a label on a report. Built by
joining pieces with plus signs, that sentence comes out inside out
— quotes, plus signs, and a str$() around every
number:
f$() lets you write the sentence the way you would say it,
with each value where it belongs, inside a pair of double brackets.
Call each [[]] a slot:
Anything you could write on the right side of an =. A
variable, some arithmetic, a function call, part of a string (the
inner brackets of [[name$[1:3]]] are fine), a whole array
or arithmetic on one, which come out as print shows them,
and even another f$():
Each slot is worked out when f$() runs, using the
variables of the code that calls it. A number comes out the way
str$() writes it — no space on either side, unlike
print — and a string comes out as it is.
f$() puts values in place; sprintf$() chooses
how a value looks. Use both: put the sprintf$() inside the
slot.
The template is an ordinary string, so it can live in a variable, a
constant, or a file, and be reused. The values are read each time
f$() runs:
A [[]] causes the
exception BADFORMAT. A mistake inside a slot — a
misspelled function, an unfinished calculation — causes one too,
with the slot's text in the message, and both are ordinary exceptions
you can catch. A name that no statement of your program assigns is an
error too: [[nmae$]] raises UNKNOWNVAR with the
misspelled name in _string$, instead of quietly printing
nothing where you expected a name (the same rule applies inside
eval()). A variable your program assigns anywhere —
even further down — is a variable, as are routine parameters and
the built-in names such as _integer. One thing that is not
an error: a single bracket is plain text — only the pair opens a
slot.
Many languages use curly braces, { }, for this.
Sheerpower uses [[]] for three reasons: it is what the
language already uses for values in web-page templates
([[variable$]]) and in macros, so it reads as the same
idea; it almost never turns up in ordinary text; and curly braces
would clash with the JSON that web programs write all day —
'{"id": [[id]]}' works as written.
[[]] slot is worked out when f$() runs
and put in as text; numbers as str$() writes them.sprintf$() inside a slot chooses decimals, commas,
width and dates.[[ and a
mistake inside a slot cause exceptions you can catch; an unknown
name is a new variable, not an error.|
Hide Description
|
|
|
Enter or modify the code below, and then click on RUN |
|
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |