- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the number of entries in a Lua table?
While there are many functions and operators that we can use to get the size of the integer entries in a particular table in lua, there's no defined method or function which works for a table that contains data that is not homogeneous in nature.
Let’s consider a simple table where we have integer values stored in it, then we will use two most common approaches to find the number of entries in that table.
Example
Consider the example shown below −
t = {} t[1] = 1 t[2] = 2 t[3] = 3 t[4] = 4 print(#t)
Output
4
But let’s take the case where instead of having the homogenous data in the table, the data is not of the same type, then in that case the # operator will result in inconsistency.
Example
Consider the example shown below −
t = {} t["yes"] = 1 t[1] = 1 t[2] = 2 t[3] = 3 print(#t)
Output
3
As we can clearly see, that the output yields an inconsistency, hence we have no choice but to write our own function to calculate the number of entries present in the table.
Example
Consider the code shown below −
t = {} t["yes"] = 1 t[1] = 1 t[2] = 2 t[3] = 3 print(#t) function tablelength(T) local count = 0 for _ in pairs(T) do count = count + 1 end return count end print(tablelength(t))
Output
3 4