Dynamic format control

Most format control directives can take parameters. These parameters are often embedded in the control string. For example, to print some text at column 16, you could do this:

* (format t "~16THello, world")
                Hello, world

What if you only know the parameter at runtime? You might be tempted to try something like this:

* (format t (format nil "~~~DTHello, world" width))    ; BOGUS
                Hello, world

Don’t do that! You can use “v” and pass the parameter as a separate argument to format:

* (format t "~vTHello, world" 16)
                Hello, world

Here’s a function that prints the bits in an integer with a configurable width:

(defun bits (integer &optional (width 8))
  (format t "~v,'0B" width integer))

* (bits 42)

* (bits 42 16)

This is one of several ways to avoid creating a format control string at runtime. (format t (format nil …) …) is almost always a mistake.