Applying D(on't) R(epeat) Y(ourself) in PlantUML

0 votes
asked Mar 24, 2022 in Question / help by boldandbusted (280 points)
edited Mar 25, 2022 by boldandbusted

I'd like to take my code from this:

app_1 .d. lb_fe_port8200
app_2 .d. lb_fe_port8200
app_3 .d. lb_fe_port8200
app_4 .d. lb_fe_port8200
app_5 .d. lb_fe_port8200

 

to something like this:

!procedure $make_clients($clients)
  !while $clients!=0
    app_$clients .d. lb_fe_port8200
    !$clients = $clients - 1
  !endwhile
!endprocedure

$make_clients(5)

However, I get this error:

    app_$clients .d. lb_fe_port8200

Syntax error?

I've tried various approaches to make the parser happy, like saying "app_[$clients] .d. lb_fe_port8200" but while that resolves to a number (I can see the number in the error message like "app_[5] .d. lb_fe_port8200") it is still a syntax error.

Any help appreciated! :) Cheers.

1 Answer

+1 vote
answered Mar 24, 2022 by Martin (8,360 points)

To concatenate a string and a variable you need to use the ## operator:

@startuml
!procedure $make_clients($clients)
  !while $clients!=0
    app_##$clients .d. lb_fe_port8200
    !$clients = $clients - 1
  !endwhile
!endprocedure

$make_clients(5)
@enduml

commented Mar 24, 2022 by boldandbusted (280 points)
OOOH! That looks great, I'll give this a shot. Thank you @Martin! :)
commented Mar 24, 2022 by boldandbusted (280 points)
Ooh, almost to perfection - but can I specify adding leading zeros (aka padded zeros)?
commented Mar 24, 2022 by Martin (8,360 points)
edited Mar 24, 2022 by Martin

There's no number formatting function that I'm aware of, so you'll have to roll your own:

@startuml
!function $right($t, $n)
!return %substr($t, %strlen($t) - $n, $n)
!endfunction

!function $pad($x, $y)
!return $right("00000"+%string($x), $y)
!endfunction

!procedure $make_clients($clients)
  !while $clients>=0
    %string("app_"+$pad($clients, 3)) .d. lb_fe_port8200
    !$clients = $clients - 5
  !endwhile
!endprocedure

$make_clients(10)
@enduml


 

Interestingly the "##" trick didn't seem to work on a function result...so I had to use %string(a+b) instead.

commented Mar 25, 2022 by boldandbusted (280 points)
Thank you once again, @Martin. While this is useful for me, I think this will be even more useful to the poor sod that has to accomodate something like 100+ interconnected devices or other objects with PlantUML. :)
...