- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- How to Fill the Entries in Parsing Table?
- How to get the number of records in a table using JDBC?
- How to get the number of columns of a table using JDBC?
- How to push a Lua table as an argument?
- Get the number of columns in a MySQL table?
- How to convert JSON string into Lua table?
- Complete the entries in the third column of the table."
- How to get number of rows in a table without using count(*) MySQL query?
- Easiest way to get number of rows in a MySQL table?
- How to not allow duplicate entries to be entered a MySQL Table?
- Table Type in Lua Programming
- How do you copy a Lua table by value?
- How to remove Lua table entry by its key?
- Get the number of rows in a particular table with MySQL
- Get number of fields in MySQL table?
