Why do Lua arrays (tables) start at 1 instead of 0?

LuaServer Side ProgrammingProgramming

Yes, the arrays in Lua start with index 1 as the first index and not index 0 as you might have seen in most of the programming languages.


Consider the example shown below −

 Live Demo

arr = {10,11,12,13,14}

In the above example, we are printing the values at indices 0 and 1, and by default, the value at the 0 index will be nil, as in Lua, the arrays start indexing from 1, not 0.



So, now we know that the arrays are 1-index based not 0-index based. But, wait, why 1-index and 0-index?

Actually, there have been several debates about which approach is better and why, when it comes to choosing between the 0-index based arrays or the 1-index based arrays, but there’s no clear cut answer.

The major reason that the arrays in Lua are 1-index based is that the language Lua itself is inspired from a language named Sol, which was designed for petroleum engineers that had no formal training in any programming languages or at all in any field of computer science. So, the people that do not have any previous knowledge about any programming language, or how the data is stored in reality, usually find it hard to understand the logic behind starting the indexing from 0, hence the Lua developers thought that it might be a better idea to start the indexing from 1 itself, which will make this case irrelevant and much easier for someone new to programming to get started with Lua without any major issues.

Also, Lua provides very much suitable methods that could help any developer using Lua to avoid the confusion between the 0-indexing and the 1-indexing, as these methods don’t even need indexing. Some of such methods are the generic for loop, or the ipairs operator.

Updated on 19-Jul-2021 11:34:35