Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I can't get my head around a 1 based language.


It helps if you realize that there are no arrays in Lua. Instead, everything is an optimized hash map that can be indexed by any value of any type. A single table can have some elements indexed by integers, others indexed by strings, function pointers (useful for a table of debug hooks), etc.

The few convenient things that expect tables to be indexed using integers starting at 1 are the # operator to get the number of elements, and the ipairs function, used in the common idiom “for index, value in ipairs(t) do . . . end”.


Normally education or human oriented languages start arrays at 1 (Smalltalk, Cobol, Lua, APL, Wolfram, etc) while hardware oriented languages start arrays at 0 (C and friends, Oberon, Forth, Scheme and so on). Human oriented languages that have to play nice with C also tend to use 0. As do Python and Basic, which contradicts my rule.

Probably the number one reason not to start arrays at 0 in an educational language is that having the last element of an array of size 10 have an index of 9 causes quite a bit of confusion.


I have to admit that this was one reason why it took me so long to start a project with Lua. Now that I've had some exposure to the language, I can say that it's not as bad as it seems, but it's also not "nothing". I frequently have to think about indices to avoid making mistakes in Lua, while in zero-based language indexing is pretty much muscle memory.


I can give you some tips to help; Tip #0 ..,.




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

Search: