Hacker News new | past | comments | ask | show | jobs | submit login

My understanding is that Lua has "tables", not arrays, which have no inherent order and that it is the standard library that uses one-based indexing for historical reasons.



You are right! It works exactly like JavaScript where an array is just an object with sequential numerical keys (though there are nuances in Lua there when it comes to having "holes" in your table).

As for 1-based indexing, you could say it's for historical reasons but essentially it was to make Lua more friendly as a beginner-friendly scripting language. Whether or not that makes any sense is up to you :) My source is this talk by the creator of the language [1]. Sorry I don't have a timestamp handy.

[1] https://www.youtube.com/watch?v=XxcSvnEIUq4


> essentially it was to make Lua more friendly as a beginner-friendly scripting language

Using an index of 0 to represent the first item is one of the most ridiculous conventions in programming (nulls being another).


0-based indexing is because of the original methods you would use to access sequential data. If you wanted to create an array with 100 1-byte integers you would literally just take 100 bytes of memory and call it an array. To access the first item in that array, you would read 1 byte at memory location `array_start + offset` and for the 1st item you would have an offset of 0 bytes. For the 2nd item, it would be accessed at an offset of 1 bytes.

Here is an example of a 10-byte array with 1-byte items starting at address "5":

    array cells xx xx xx xx xx xx xx xx xx xx
    item number  1  2  3  4  5  6  7  8  9 10
    mem offset   0  1  2  3  4  5  6  7  8  9
    mem address  5  6  7  8  9 10 11 12 13 14
To get the 1st item, just take "5 + 0" to get the address to read from, and etc.

It's mostly because it was easier to just think in offsets starting from 0 rather than think in item numbers and have to always remember to use the "item number - 1" as the memory offset for that item.


Until you have to work in multiple dimensions. 1-based indexing in more than 1D is the worst


Zero-indexing doesn't just mean that the pointer to the first item in the block is the same as the pointer to the block itself, it also means that pointers to strides within the block have the same property.

Which is what you're saying, but yeah— I think zero indexing is one of those things that's like... a bit sucky, but the alternative is enough-worse that it makes sense to just get used to it.


Whoa! 20 years in the game and I never thought about this—of course you want zero indexing when you have a 2D (or more) graph! I'll forgive myself, though, since I'm a web developer who has only ever had to do the most basic math.


Yeah, that’s why Fortran never caught on.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: