
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Concatenation of Tables in Lua Programming
We can append two tables together in Lua with a trivial function, but it should be noted that no library function exists for the same.
There are different approaches to concatenating two tables in Lua. I’ve written two approaches that perform more or less the same when it comes to complexity.
The first approach looks something like this −
function TableConcat(t1,t2) for i=1,#t2 do t1[#t1+1] = t2[i] end return t1 end
Another approach of achieving the same is to make use of the ipairs() function.
Example
Consider the example shown below −
for _,v in ipairs(t2) do table.insert(t1, v) end
We can use either of these approaches. Now let’s use the first one in a Lua example.
Example
Consider the example shown below −
t1 = {1,2} t2 = {3,4} function TableConcat(t1,t2) for i=1,#t2 do t1[#t1+1] = t2[i] end return t1 end t = TableConcat(t1,t2) for _, v in pairs(t1) do print(v) end
Output
1 2 3 4
Advertisements