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

ArgumentTypeDefaultDescription
VARvariable namerequiredThe variable with the list.
INDEXindex, or a list of indexesnoneThe place of the element, one level of the path each.
VALUEany valuerequiredThe 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

Facts

Capability
None.
Tcl release
Tcl 9.1 and 8.6.
Since
ztcl 1.0.0-beta.1

See also