====== Tcl lists tips ======
This page is part of the Tcl/Tk page of the Airplug documentation.\\
[[en:doc:pub:tcltk:start|Back to the Tcl/Tk page]] /
[[en:doc:summary|Back to Airplug documentation page]].
---
A list is defined by
set lst [list a b c d]
Adding an element is done using ''lappend'', which modify the list (here ''lst'' variable is referred without ''$''):
lappend lst "e"
puts stdout "lst = $lst" # lst = a b c d e
Replacing some elements can be done using ''lreplace''. However this call does not modify the list. Instead it returns a new list.
set newlst [lreplace $lst 1 2 "z"]
puts stdout "lst = $lst" # lst = a b c d e
puts stdout "newlst = $newlst" # newlst = a z d e
Obtaining the index of an element in a list can be done using ''lsearch'':
set i [lsearch $lst "b"]
puts stdout "i = $i" # i = 1
The following code allows to remove an element from the list (supposing it is unique):
set element "b"
set i [lsearch $lst $element]
set lst [lreplace $lst $i $i]
puts stdout "lst = $lst" # lst = a c d e
Finally, to remove all occurences of a given element, one may proceed as follows:
set lst [list a b c b d b b]
puts stdout "lst = $lst"
set element "b"
while { [set i [lsearch $lst $element]] != -1 } {
set lst [lreplace $lst $i $i ]
puts stdout "$element found at index i = $i; now lst = $lst"
}
which gives the following output:
lst = a b c b d b b
b found at index i = 1; now lst = a c b d b b
b found at index i = 2; now lst = a c d b b
b found at index i = 3; now lst = a c d b
b found at index i = 3; now lst = a c d
----
This page is part of the Tcl/Tk page of the Airplug documentation.\\
[[en:doc:pub:tcltk:start|Back to the Tcl/Tk page]] /
[[en:doc:summary|Back to Airplug documentation page]].