-- Indices start at 1 !! SO CRAZY!
As of a few years ago, I use Lua regularly in my day job and this one still baffles me. In Lua, the first element in a list is index 1, rather than 0. -- Indices start at 1 !! SO CRAZY!
As of a few years ago, I use Lua regularly in my day job and this one still baffles me. In Lua, the first element in a list is index 1, rather than 0.I was once implementing some math algorithm whose description had various subscripted variables. Some ran from 0 to whatever, and some ran from 1 to whatever. I was implementing in C++, with each of these variables becoming an array. I didn't want to write var[i-1] all over the place for the ones that ran from 1 in the book--it was a tricky algorithm and for maximum clarity I wanted my code to read as close to the book as possible.
What I did was overload the () operator to make it a 1-based array access operator. I.e., var(i) == var[i-1].
That worked out reasonably, although it probably would have been better just to make the arrays for the 1-based variables one longer and just ignore var[0]. In other words, if var in the text has subscripts that run from 1 through 10, make the var array in C++ 11 long, and just use var[1] through var[10].
I think it would be better if the end-points were “low” and “high” rather than “start” and “stop”, so the reverse of `range(0, 5)` would simply be `range(0, 5, -1)`.
Lua is a small language, and tables are the basic building blocks for arrays, dictionaries, classes, modules, ... 1-based indexing is IMHO a small price to pay for such flexible and efficient syntax, with small cognitive load)
var a : array of integer;
b : array[0..9] of integer;
c : array[1..10] of integer;
begin
writeln(low(a)); // 0
writeln(high(a)); // -1
writeln(low(b)); // 0
writeln(high(b)); // 9
writeln(low(c)); // 1
writeln(high(c)); // 10
end.