Implementing a counter in markup text: Difference between revisions

simultanous calls are backward!
mNo edit summary
Line 1: Line 1:
This snippet shows how to implement a counter in LilyPond for use in markup texts. Whenever you call the <code>\counter #&quot;name&quot;</code> markup function, the counter named <code>name</code> will be increased by one and the new value will be printed as a text markup. The first call will print “1” by default. Example:
This snippet shows how to implement a counter in LilyPond for use in markup texts. Whenever you call the <code>\counter "name"</code> markup function, the counter named <code>name</code> will be increased by one and the new value will be printed as a text markup. The first call will print “1” by default. Example:


<code>\markup { Initial value of the counter: \counter #&quot;mycounter&quot;. Second call: \counter #&quot;mycounter&quot; }</code>
\markup {
  Initial value of the counter: \counter #"mycounter".
  Second call: \counter #"mycounter" }


The snippet also implements a <code>\setcounter #&quot;name&quot; newvalue</code> markup command to set the the counter to a specific value and print it out.
The snippet also implements a <code>\setcounter #"name" newvalue</code> markup command to set the the counter to a specific value and print it out.


One can have an arbitrary number of simultaneous counters, each indicated by its own name (as a string).
One can have an arbitrary number of simultaneous counters, each indicated by its own name (as a string).
Line 9: Line 11:
The storage of the counter values is implemented as a global alist <code>counter-alist</code> (Scheme/Guile's concept of a hash), where the <code>counter</code> command simply extracts the current value, increases it by one and stores it back in the alist.
The storage of the counter values is implemented as a global alist <code>counter-alist</code> (Scheme/Guile's concept of a hash), where the <code>counter</code> command simply extracts the current value, increases it by one and stores it back in the alist.


<lilypond version="2.24" full>
<lilypond version="2.24">
%% http://lsr.di.unimi.it/LSR/Item?id=543
 
\paper { tagline = ##f }
 
%here starts the snippet:
 
#(define counter-alist '())
#(define counter-alist '())