 # How to connect 2 tables to a table?

Hi! As you can see the title, I’m confusing with table connecting.

I have some tables like that: `{1, 2, 3} {4, 5, 6}`,
but I just want to connect tables like: `{1, 2, 3, 4, 5, 6}`.

I have tried to figure it out with table.unpack(), but it wasn’t working, or I might did a mistake.
How do I? Any ideas? Thank you.

1 Like

One lazy solution would be to loop through the second table and insert everything into the first table.

``````for i, v in pairs(t2) do
table.insert(t1, v)
end
``````

If you wanted to make a copy instead of adding to the first table

``````local t3 = {}
for i, v in pairs(t1) do
table.insert(t3, v)
end
for i, v in pairs(t2) do
table.insert(t3, v)
end
``````

Another way would be concatenating both tables together, and `string.split`ing them.

``````local t3 = string.split(table.concat(t1," ")..table.concat(t2," ")," ")
``````

Only problem is now the numbers are strings, thus a better solution is

``````local t3 = {}
(table.concat(t1," ")..table.concat(t2," ")):gsub("(%d+) ", function(s) table.insert(t3, tonumber(s)) end)
``````

But for simplicity go for the first or second one!

5 Likes

If you want them inserted in the correct order, @starmaq solution is correct but you need to use the ipairs iterator:

``````local Table1 = {1,2,3}
local Table2 = {4,5,6}
--Moving all values from Table 2 to Table 1
for i, v in ipairs(Table2 ) do
table.insert(Table1, v)
end
--Now all the values will be in the first table
for i,v in ipairs (Table1) do
print(v)
end
``````
2 Likes

Other solution could be `table.move`:

``````local function combine(a1, a2)
local new = table.create(#a1 + #a2)
table.move(a1, 1, #a1, 1, new)
table.move(a2, 1, #a2, 1, new)
return new
end
``````
6 Likes

Thank you all for helpful advices! I will remember that ways when I connect tables. Thank you again!
(All of them are amazing, actually.)

You also can do;

``````local Table1 = {123}
local Table2 = {123,12,3123}
print({table.unpack(Table1),table.unpack(Table2)})
``````
5 Likes

This supports multiple tables if you didn’t want to keep repeating yourself

``````local function combine(...)
local tables = {...}
local totalContentCount = 0

for _,t in pairs(tables) do
totalContentCount += #t
end
local combined = table.create(totalContentCount)

for _,t in pairs(tables) do
table.move(t, 1, #t, #combined, combined)
end

return combined
end

-- usage example
local exampleTableOne = {'bool', 'string', 'number', 'instance'}
local exampleTableTwo = {'One', 1, 14, 43, "ABC", "D"}
local exampleTableThree = {14 % 2 == 0, ":)"}

local result = combine(exampleTableOne, exampleTableTwo, exampleTableThree)
print(result)
``````
``````local function combine(...)
local t = {}
for _, v in pairs(...) do
for i = 1, #v do
t[#t+1] = v[i]
end
end
return t
end
``````