How do i merge two tables together?

How do i merge two tables together? Example:

local table1 = {
	"hello1",
	["hello2"] = {
		yes = true
	}
}
local table2 = {
	"hello3",
	"hello4"
}
local mergedTable = {
	"hello1",
	["hello2"] = {
		yes = true
	},
	"hello3",
	"hello4"
}

3 Likes

Using “FOR” loop and table.insert, is the most easily way.

local table1 = {
	"hello1",
	["hello2"] = {
		yes = true
	}
}
local table2 = {
	"hello3",
	"hello4"
}
local FinalTable = {}

for _, TableChild in pairs(table1) do
    table.insert(FinalTable,table1)
end

for _, TableChild in pairs(table2) do
    table.insert(FinalTable,table2)
end

19 Likes
local table1 = {
	"hello1",
	"hello2"
}

local table2 = {
	"hello3",
	"hello4"
}

table.move(table2, 1, #table2, #table1 + 1, table1)
for _, value in ipairs(table1) do
	print(value)
end

table.move() is also available for arrays.

19 Likes

Hm i didn’t knew that, this is a new function? I am not who is asking but it’s will help me too. :stuck_out_tongue:

2 Likes

It’s a backported feature from Lua 5.3, I’m not sure exactly when it was added to Roblox Lua.

You can find its documentation here.
https://www.lua.org/manual/5.3/manual.html
https://developer.roblox.com/en-us/api-reference/lua-docs/table

3 Likes

Oh, ty. I studed with lua 4.9 so i didn’t knew that.

1 Like

EDIT: THIS DOES NOT WORK

use table.move as described above

hey, sorry to bump this but in case anyone (like me) stumbles across this wondering how to do it,

you can also use (im not sure which of the options is the most optimized one but i’d say this one looks the cleanest) table.pack in combination with table.unpack, like so:

local merged_table = table.pack(table.unpack(table1), table.unpack(table2))

*this though will only work for arrays, not dictionaries

9 Likes

I apologize for bumping this, but here goes:


Copy and paste code if anyone needs it
local table1 = createButtonKeybindsArray(TopMiddleKeybindBar, ToolBarKeybindsFolder)
local table2 = createButtonKeybindsArray(BottomMiddleKeybindBar, ToolBarKeybindsFolder)

print(table1)
print(table2)

local merged_table = table.pack(table.unpack(table1), table.unpack(table2))

print(merged_table)

Does anyone have any idea why the last part completely breaks?
Thanks!

my mistake, really sorry for that, i did some research and the pack function does say its going to return a table of number indexes and a “n” index that is the length i guess?
image
furthermore when you unpack multiple tables like that it only ever really seems to pack the first value out of the first table… this is all weird to me as i was pretty sure i tested this approach but i guess its invalid (i couldnt get it to work), use table.move as described in the posts above i guess

1 Like