lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On 5/3/06, Reuben Thomas <> wrote:
Icon and Lua both demonstrate the benefit of 1-based indexing over
0-based: the ability to count forward from the start of a string and
backwards from the end symmetrically: 1 points to (just before) the
first character and -1 to (just before) the last. Hence, 0 points to
the end of the string, which seems a little odd, but if you use
zero-based addressing, you can no longer point to the end of the string.

Actually you can.  Consider a string or array of four elements,
e.g. "ABCD":

 A   B   C   D        the string
0   1   2   3   4      forward indexing
-5  -4  -3  -2  -1     backward indexing

All you lose is the `symmetry' of counting, which is
questionable in the 1-based variant anyway.  Why is it
questionable?  When you go backwards, `before' should
mean `after', and `pointing just before' should be
`pointing just after' a character.  In these terms, with
1-based indexing forward and 0-based backward,
1 points to (just before) the first character while -1
points to (just after) the last but one.
Besides, the very fact of using the 0 -- be it for
forward or for backward indexing -- destroys symmetry:
(negatives ballance with positives, 0 stands for itself).
True symmetry is chimeric here, regardles of 0/1-based

There's another argument about whether you point at characters or the
gaps between them: if you insist on pointing at characters, you lose the

  string.len(string.sub(s, a, b)) == b - a

for a, b of the same sign ...

Pointing at the gaps suggests half-open ranges
(one end is included, the other is excluded), and so,
to the extent half-open ranges suggest 0-based
indexing, your argument actually supports 0-based
indexing :)

APL, a language whose numerical properties are most
carefully thought out, defaults to 1-based.

APL allows for both 1-based and 0-based indexing.
Its modern successors, J and K, however, both use
0-based only.