lset
Sets one element of the list in a variable, also in nested lists.
lset VAR ?INDEX ...? VALUE
Description
Sets the element at INDEX of the list in the variable VAR to VALUE, and gives the new list. Each further INDEX goes one level down into a nested list, and one INDEX that is a list of indexes is the same path, as for lindex.
The index end+1, or the count of elements, adds an element at the end. Each other index must be in the list: an index below 0 or more than one past the end is an error. With no INDEX, or with an empty list as INDEX, VALUE replaces the whole value of VAR.
VAR must have a value. A value on the path that is one word is a list of one element, so lset l 0 0 0 z works on the list {a b}.
Arguments
| Argument | Type | Default | Description |
|---|---|---|---|
| VAR | variable name | required | The variable with the list. |
| INDEX | index, or a list of indexes | none | The place of the element, one level of the path each. |
| VALUE | any value | required | The new element. |
Returns
The new value of VAR.
Examples
% set l {a b c}
> lset l 1 x
a x c
% set l {{a b} {c d}}
> lset l 1 0 x
{a b} {x d}
% set l {{a b} {c d}}
> lset l {1 0} y
{a b} {y d}
% set l {a b}
> lset l end+1 c
a b c
% set l {a b}
> lset l x
x
Errors
% set l {a b}
> lset l 5 c
list index out of range
-errorcode NONE
% unset -nocomplain nv
> lset nv 0 x
can't read "nv": no such variable
-errorcode NONE
% lset
wrong # args: should be "lset listVar ?index? ?index ...? value"
-errorcode TCL WRONGARGS
Differences from Tcl
- An index out of range has
-errorcode NONE, where Tcl 8.6.16 givesTCL OPERATION LSET BADINDEXand Tcl 9.0.4 givesTCL VALUE INDEX OUTOFRANGE(issue 658). - In Tcl 9.0.4 the message of an index out of range names the index:
index "5" out of range(issue 665).
Facts
- Capability
- None.
- Tcl release
- Tcl 9.1 and 8.6.
- Since
- ztcl 1.0.0-beta.1