3 ms·
Another advantage is with ranges: 0-based indexing and exclusive ranges work well. This is apparent with cursor position in text selection Consider: Chara
by armchairhacker 4y ago
Another advantage is with ranges: 0-based indexing and exclusive ranges work well. This is apparent with cursor position in text selection
Consider:
Characters h e l l o
Cursor index 0 1 2 3 4 5
Char index 0 1 2 3 4
Range [0,3) [0,1,2]
Range [2,5) [2,3,4]
Range [1,1) []
If we used 1-based indexing and exclusive ranges, it leads to ranges where the end index is greater than the string's length...
Characters h e l l o
Cursor index 0 1 2 3 4 5
Char index 1 2 3 4 5
Range [1,4) [1,2,3]
Range [3,6) (!) [3,4,5]
Range [2,2) []
but if we use inclusive ranges, it leads to ranges where the end index is less than the start index...
Characters h e l l o
Cursor index 0 1 2 3 4 5
Char index 1 2 3 4 5
Range [1,3] [1,2,3]
Range [3,5] [3,4,5]
Range [2,1) (!) []
Also:
Characters h e l l o
Cursor index 0 1 2 3 4 5
0-based range [0,3) [0,1,2]
1-based range [1,4) [1,2,3]
for the 0-based range [0, 3), the left array bracket is at cursor index 0, and the right bracket is at index 3. With 1-based indexing it doesn't work like that because the range is [1, 4)
- samatman 4y agoThis is the bane of my existence working with Lua. Iterating an array or adding to the end are fine, we have ipairs and insert for that, but ranges on strings I'm constantly having to think harder and write more code than necessary. I love the language, wouldn't trade it for another, but the 1-based indexing on strings, which represents an empty string at position 3 as (3,2), it's egregious. Not as egregious as a dynamic language where 0 is false though.
- chii 4y ago> a dynamic language where 0 is false though. well, C also considers 0 being false (and you can argue that C is "dynamic"!).
- yccs27 4y agoYeah, offsets are just easier to mathematically manipulate than ordinals. It's not just pointer arithmetic where it matters that item i corresponds to start+i*step. Any time you want to convert between integer indices and general linearly-spaced values, 0-based indexing is more convenient.