(defun fmt-pretty (FMT &rest stuff)
(progv '(*float-format*) (list FMT)
(apply #'format stuff)))
This code is cryptic. Let’s break it down a line at a time:
.
(defun fmt-pretty (FMT &rest stuff)
Defines a function called “fmt-pretty” with arguments “FMT” and “stuff”.
“&rest” says that “stuff” may be zero or more values (see: https://www.audacity-forum.de/download/edgar/nyquist/nyquist-doc/xlisp/xlisp-ref/xlisp-ref-223.htm)
.
(progv '(*float-format*) (list FMT)
This sets float-format to the value of FMT.
float-format is a global variable used by Nyquist to specify the printed decimal format. See: https://www.audacity-forum.de/download/edgar/nyquist/nyquist-doc/xlisp/xlisp-ref/xlisp-ref-119.htm
This could have been written more simply as:
(setf *float-format* FMT)
but I assume that the author wanted to ensure that float-format was only set to FMT within the scope of his function.
If he simply used (setf float-format FMT), then float-format would be set globally to the value of FMT.
.
(apply #'format stuff)
This applies the function FORMAT (https://www.audacity-forum.de/download/edgar/nyquist/nyquist-doc/xlisp/xlisp-ref/xlisp-ref-121.htm) to the elements of the list “stuff”.
.
Here’s an example of how it works:
(defun fmt-pretty (FMT &rest stuff)
(progv '(*float-format*) (list FMT)
(apply #'format stuff)))
(setq FMT-val "%.3f") ;format directive = 3 decimal places
(setf val 1.23456789012345) ;set val to a number with lots of decimals
(fmt-pretty FMT-val t "~a" val) ;call the function "fmt-pretty, passing 4 values
The final line calls the function “fmt-pretty” with 4 arguments:
-
FMT-val, evaluates to the “3 decimal places” format directive. This is a string value.
-
t, the destination. This is the boolean value “true”.
-
“~a”, a string. Note that this contains the format directive placeholder “~a”.
-
val, evaluates to the decimal number 1.23456789012345
The first two lines of the function “fmt-pretty” are explained above.
The third line of the function expands “stuff” and applies the function FORMAT to the arguments. In other words, the final line expands to:
(format t "~a" val)
Because float-format has (temporarily) been set to “%.3f”, (format t “~a” val) prints val (that has a value of 1.23456789012345) with three decimal places. The destination “true”, sets the output of format to standard-output, which in Audacity is the debug output.
.
If you paste this code into the Nyquist Prompt and click the Debug button, you should see 1.235 printed in the debug window that opens. (note that the final digit has been rounded up to “5”).
(defun fmt-pretty (FMT &rest stuff)
(progv '(*float-format*) (list FMT)
(apply #'format stuff)))
(setq FMT-val "%.3f") ;format directive = 3 decimal places
(setf val 1.23456789012345) ;set val to a number with lots of decimals
(fmt-pretty FMT-val t "~a" val) ;call the function "fmt-pretty, passing 4 values