Just another example of missing string interpolation
Andrey Zherikov
andrey.zherikov at gmail.com
Thu Oct 12 23:54:15 UTC 2023
On Thursday, 12 October 2023 at 13:39:46 UTC, Andrea Fontana
wrote:
> Real life example. Render a string like this:
>
> ```
> \x1b[2K\r\x1b[1mProgress:\x1b[0m 50% \x1b[1m\tSpeed:\x1b[0m
> 15.5 KB/s
> ```
>
> now (error prone and difficult to debug, try to code it!):
>
>
> ```
> stderr.write(format("%s\r%sProgress:%s %5.1f%% %s\tSpeed:%s
> %6.1f %s%s", clear, white, clear, progress, white, clear,
> curSpeed, unit));
> ```
>
> (or with string concat, good luck!)
>
> vs:
>
> ```
> stderr.write("${clear}\r{$white}Progress:${clear}${progress}%
> \t${white}Speed:${clear} ${curSpeed} ${unit}");
> ```
>
> Andrea
If you are using `write*` then you can simply do this:
```d
stderr.write(clear,"\r",white,"Progress:",clear," ",progress,"%
",white,"\tSpeed:",clear," ",curSpeed," ",unit);
```
If you want just to get a string - use `text`:
```d
stderr.write(text(clear,"\r",white,"Progress:",clear,"
",progress,"% ",white,"\tSpeed:",clear," ",curSpeed," ",unit));
```
The result is the same so IMHO `text` is good alternative to
string interpolation.
You can also wrap styling into functions to make code more
readable:
```d
string white(A...)(A args)
{
return text("\x1b[1m", args, "\x1b[0m");
}
stderr.write(clear,"\r",white("Progress: "),progress,"%
\t",white("Speed: "),curSpeed," ",unit);
```
More information about the Digitalmars-d
mailing list