- Trending Categories
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
What is the difference between pairs() vs. ipairs() in Lua?
In Lua, we make use of both the pairs() and ipairs() function when we want to iterate over a given table with the for loop. Both these functions return key-value pairs where the key is the index of the element and the value is the element stored at that index table.
While both of them have some similarities, it is also good to know that they have some very notable differences that we should be aware of.
The first difference between the pairs() and ipairs() function is that the pairs() function doesn’t maintain the key order whereas the ipairs() function surely does.
Example
Consider the example shown below −
u={} u[1]="a" u[3]="b" u[2]="c" u[4]="d" u["aa"] = "zz" u[7] = "e" for key,value in ipairs(u) do print(key,value) end print(“---”) for key,value in pairs(u) do print(key,value) end
In the example above, the ipairs() function will print the order of the key in numeric order, whereas the pairs() function doesn’t guarantee it.
Also, if we look at the example a bit more closely, we will see the second difference, and that is that the ipairs() function doesn’t return non-numeric keys that are present in the table.
Output
Consider the output for the reference.
1 a 2 c 3 b 4 d --- 1 a 2 c 3 b 4 d 7 e aa zz
- Related Articles
- What is difference between vs. ?
- What is the Difference between Git Vs Subversion?
- Difference between . and : in Lua programming
- Difference between \'__eq__\' VS \'is\' VS \'==\' in Python
- What is the difference between local storage vs cookies?
- Difference between Python and Lua
- What is the difference between MySQL TINYINT(2) vs TINYINT(1)?
- What is the difference between Selenium's Remote Control vs WebDriver?
- Lua pattern matching vs regular expression
- Difference Between Set vs List vs Tuple
- Difference Between Coronavirus vs Flu vs Cold vs Allergies
- bashrc vs. bash_profile What Is Difference
- Difference between JQuery vs Cypress
- Find Maximum difference between tuple pairs in Python
- What is the difference between supplementary angles and complementary angles and also linear pairs of angles?
