Hacker News new | ask | show | jobs
by JulianMorrison 4893 days ago
Indexing from 1 and 0 seem to me to reflect two different equally valid viewpoints. Offsets against a base address in memory (the C family) versus labels for boxes (Lua and friends). Naturally, stating from a base address, the offset is 0. Equally naturally, if you're labelling boxes with numbers, you number the first one "1". For Lua, given the tables are also at the same time hashes (with explicit labels), treating them as numbered boxes makes sense.
1 comments

I think also the construction of the for loop makes it more natural. Lua is "for i = i, n" vs the more complex and off-by-1 prone "for (i = 1; i < n; i++)" where you need the less than vs an equality.
The unintuitive thing about this choice is that "for i = n,m" calls the loop body "m-n+1" times. The "for (i = n; i < m; i++)" does it "m-n" times.

A more elaborate argument: http://www.cs.utexas.edu/~EWD/transcriptions/EWD08xx/EWD831....

If your for loop is for a 0-based language, it's wrong because it starts with 1.

If it's for a 1-based language, it's wrong because it compares with "<" and not "<=".

So, I guess that proves your point that it's error-prone. :)

In C, the idiomatic way is (as you surely know) "for(i = 0; i < n; ++i)".

typo, the second one was supposed to be 0 based... although that shows how off by 1 errors occur.