lua-users home
lua-l archive

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


On 3/25/2017 1:57 PM, Tim Hill wrote:
> 
>> On Mar 25, 2017, at 3:53 AM, Joseph Manning <manning@cs.ucc.ie> wrote:
>>
>> On 2017-Mar-25 (Sat) at 12:42 (+0200), steve donovan wrote:
>>
>> Steve,
>>
>>   Yes!  In fact, 1-based indexing is one of the ( several ) reasons
>>   that I like Lua.  I detest either using, or teaching, the unnatural
>>   "0 to length-1" pattern of many other "high-level"(?) languages.
>>
>>   But you're right -- "each to their own".  0 versus 1 debates are
>>   similar to emacs versus vi debates :-)
>>
>> Joseph
>>
> 
> To my mind both have their place. 0-based indexing makes perfect sense in C, where indexing is little more than syntactic sugar over pointer+offset anyway — but really that’s because C was designed (to my mind) as a reified assembly language anyway. However, once you get into higher abstractions (such as any decent script language) 0-based ceases to have much validity imho.

I usually prefer to not debate 0 vs 1 based indexing but I also think
that believing 0 based indexing ceases to make sense for higher level
languages is ignoring important mathematical properties of programming
and algorithms.

In this case, it's the fact that a sequence of N things has N+1
positions, at the beginning of each element and just past the last
element. This allows the use of open ended ranges, meaning [a, b), where
a is in the range and b is not. This allows specifying the empty range.
All ranges in Lua are [a, b] and therefore, specifying the empty range
is either impossible or requires using [a, a-1], which most functions
don't specify as being well-formed.

So, yes, if all you ever need is iteration over a sequence, then it
doesn't matter what base is used. But when ranges (including empty ones)
are desired, the natural affinity between 0-based indexing and open
ended ranges does make things easier without lots of special cases.