TIP 566: Index usage in lset

Login
Author:         Jan Nijtmans <[email protected]>
State:          Withdrawn
Type:           Project
Vote:           Pending
Created:        19-Feb-2020
Post-History:   
Keywords:       lset
Tcl-Version:    8.7
Tcl-Branch:     lset-index

Abstract

This TIP proposes to change the lset command, such that situations previously resulting in an error result in a more logical outcome.

Rationale

Commands like string insert and linsert are very flexible in how index underflow and overflow is handled. For example

% linsert {a b c} 2 x
a b x c
% linsert {a b c} 100 x
a b c x
% linsert {a b c} -10 x
x a b c 

We see that indices larger than the list size result in elements added at the end of the list. While all negative indices result in elements added at the beginning.

lset does not have that flexibility:

% set x {a b c}
% lset x 2 x
a b x
% lset x 3 y
a b x y
% lset x 4 z
list index out of range
% lset x -1 z
list index out of range

Specification

The function Tcl_GetIntForIndex() is modified such that for any index value resulting in a negative number, value -1 is returned. Also, any index value resulting in a number bigger than the list size will result in exactly the list size. This means that all commands using Tcl_GetIntForIndex() will automatically gain part the functionality as built-in by linsert and string insert.

Also, lset is modified not to consider index -1 as an error, but duplicate the functionaly as done for large indices: Using negative indices results in adding elements to the left side of the list.

New situation:

% set x {a b c}
% lset x 2 x
a b x
% lset x 3 y
a b x y
% lset x 4 z
a b x y z
% lset x -1 z
z a b x y z

Compatibility

With this change, lset will not return the list index out of range error-message any more. Any application depending on this error-situation will be affected.

Implementation

See the lset-index branch.

This branch targets 8.7.

Copyright

This document has been placed in the public domain.