Next: , Up: Controlled Formatting   [Contents][Index]


6.4.4.1 Conditional Directive

~[...~;...~:;...~]

This directive is closed by a corresponding ‘~]’, and in between are a number of clauses separated by ‘~;’. The job of the ‘~[’ directive is to pick one of the clauses, which is then processed by FORMAT

With no modifiers or parameters, the clause is selected by numeric index; the ‘~[’ directive consumes a format argument, which should be a number, and takes the ‘nth’ (zero-based) clause where ‘N’ is the value of the argument. If the value of the argument is greater than the number of clauses, nothing is printed. However, if the last clause separator is ‘~:;’ instead of ‘~;’, then the last clause serves as a default clause.

(format nil "~[cero~;uno~;dos~]" 0) ==> "cero"
(format nil "~[cero~;uno~;dos~]" 1) ==> "uno"
(format nil "~[cero~;uno~;dos~]" 2) ==> "dos"
(format nil "~[cero~;uno~;dos~]" 3) ==> ""
(format nil "~[cero~;uno~;dos~:;mucho~]" 3)   ==> "mucho"
(format nil "~[cero~;uno~;dos~:;mucho~]" 100) ==> "mucho"
~#[...~;...~:;...~]

It’s also possible to specify the clause to be selected using a prefix parameter. ‘#’ used as a prefix parameter means the number of arguments remaining to be processed.

(defparameter *list-etc*
   "~#[NONE~;~a~;~a and ~a~:;~a, ~a~]~#[~; and ~a~:;, ~a, etc~].")
~:[...~]

With a colon modifier, the ‘~[’ can contain only two clauses; the directive consumes a single argument and processes the first clause if the argument is NIL and the second clause is otherwise.

(format t "~:[FAIL~;pass~]" test-result)
~@[...~]

Finally, with an at-sign modifier, the ‘~[’ directive can have only one clause. The directive consumes one argument and, if it’s non-NIL, processes the clause after backing up to make the argument available to be consumed again.

(format nil "~@[x = ~a ~]~@[y = ~a~]" 10 20)   ==> "x = 10 y = 20"
(format nil "~@[x = ~a ~]~@[y = ~a~]" 10 nil)  ==> "x = 10 "
(format nil "~@[x = ~a ~]~@[y = ~a~]" nil 20)  ==> "y = 20"
(format nil "~@[x = ~a ~]~@[y = ~a~]" nil nil) ==> ""

Next: Iteration Directive, Up: Controlled Formatting   [Contents][Index]