I want to use formatted output in a loop to generate a string. Manual says it can be easily done by giving format
function a string with a fill pointer as a destination. Unfortunately, it is not transparent from the manual how to initialize this string in the first place.
I tried (string "")
and (format nil "")
with no luck.
(make-array 0 :element-type 'character :fill-pointer 0)
did work for me, but it just doesn't feel right.
What is the proper way to initialize a string with a fill pointer?
(make-array estimated-size-of-final-string
:element-type 'character :fill-pointer 0)
(with :adjustable t
too if the estimate is inaccurate) is one way; for accumulating output to produce a string it may be more idiomatic to use with-output-to-string
:
(with-output-to-string (stream)
(loop repeat 8 do (format stream "~v,,,'-@A~%" (random 80) #\x)))
=>
"----------------------------------x
--------x
--------------------------------------x
----------------------------------------------------------------x
--------------x
-----------------------------------------x
---------------------------------------------------x
-----------------------------------------------------------x
"
(make-array 0 :element-type 'character :fill-pointer 0)
is the canonical way (well, it's quite possible to use an initial non-zero length and use :initial-contents
with a string value). It's also possible to specify the fil-pointer value as t
, that will set the fill-pointer at the end of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With