views:

360

answers:

3

Hi,

I don't understand the rational behind the decision of this part of Lua. Why does indexing start at 1? I have read(as many others did) this great paper. It seems to me a strange corner of a language that is very pleasant to learn and program. Don't get me wrong, Lua is just great but there has to be an explanation somewhere. Most of what I found(on the web) is just saying the index starts at 1. Full stop.

It would be very interesting to read what its designers said about the subject.

Note that I am "very" beginner in Lua, I hope I am not missing something obvious about tables.

+4  A: 

My understanding is that it's that way just because the authors thought it would be a good way to do it, and after they rolled the language out to the public that decision calcified considerably. (I suspect there would be hell to pay were they to change it today!) I've never seen a particular justification beyond that.

dash-tom-bang
As far as I know, this is correct.
Amber
Possible justification: C only did it because an array is basically just a pointer and `array[0] == array + 0;`, and 1-based counting is more natural when array is really a hash table.
Judge Maygarden
Lua indices are actually indices. In C when you say index what you really mean is an offset.
Alex
+7  A: 

In Programming in Lua's first discussion of tables, they mention:

Since you can index a table with any value, you can start the indices of an array with any number that pleases you. However, it is customary in Lua to start arrays with 1 (and not with 0, as in C) and several facilities stick to this convention.

Later on, in the chapter on data structures, they say almost the same thing again: that Lua's built-in facilities assume 1-based indexing.

Anyway, there are a couple conveniences to using 1-based indexing. Namely, the # (length) operator: t[#t] access the last (numeric) index of the table, and t[#t+1] accesses 1 past the last index. To someone who hasn't already been exposed to 0-based indexing, #t+1 would be more intuitive to move past the end of a list. There's also Lua's for i = 1,#t construct, which I believe falls under the same category as the previous point that "1 to the length" can be more sensible than indexing "0 to the length minus 1".

But, if you can't break the mindset of 0-based indexing, then Lua's 1-based indexing can certainly be more of a hindrance. Ultimately, the authors wanted something that worked for them; and I'll admit I don't know what their original goal was, but it's probably changed since then.

Mark Rushakoff
+7  A: 
Norman Ramsey
Thanks sir, I started reading The Evolution of Lua.
AraK
This is just a historical, marketing reason. No rational reason, especially at current time. And it seems even you're trying to avoid 1-based indexing instead of utilizing it :)
Eonil