

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why do Lua arrays (tables) start at 1 instead of 0?
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.
Example
Consider the example shown below −
arr = {10,11,12,13,14} print(arr[0]) print(arr[1])
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.
Output
nil 10
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.
- Related Questions & Answers
- Why do we use WebDriver instead of Selenium IDE?
- Concatenation of tables in Lua programming
- Why we mention in MySQL WHERE 1=0?
- Why does the indexing start with zero in C# arrays?
- Construct ∈-NFA of Regular Language L = 0(0+1)*1
- Read-only tables in Lua programming
- Is it possible to have JavaScript split() start at index 1?
- Convert RE 1(0+1)*0 into equivalent DFA.
- Sorting numbers in descending order but with `0`s at the start JavaScript
- Why do the desert plants bloom at night?
- Can we call run() method directly instead of start() in Java
- Design NFA with Σ = {0, 1} and accept all string of length at least 2.
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Sort an arrays of 0’s, 1’s and 2’s using Java
- Design a DFA of a string with at least two 0’s and at least two 1’s