Is there a way to loop through two tables in 1 pairs loop

If I have two tables

local rice = {1,5}
local pie = {8,6}

Is it possible to combine the two tables into one without using an extra for loop?

for i,v in pairs(rice+pie) do
print(v)
end

Figured it out, here’s what you’d do:

local rice = {1,5}
local pie = {8,6}
local combinedtable = {unpack(rice), unpack(pie)}

for i,v in pairs(combinedtable) do
print(v)
end

For some reason it prints ‘1, 8, 6’ but not ‘5’ that’s a bit weird…

You could use recursion and setting up all the tables in one table

local rice = {1, 5}
local pie = {8, 6}
local combinedtable = {rice, pie}

local function recursion(table)
	for _, value in pairs(table) do
		if typeof(value) == "table" then
			recursion(value)
		else
			print(value)
		end
	end
end

recursion(combinedtable)

Btw, there is someone who already found a solution to this

I suggest making a function that creates a new table which combines two or more tables:

local function CombineArrays(...: { [number]: any }) : { [number]: any }
	local newArray = {}
	
	for _, array in { ... } do
		if not (typeof(array) == "table") then
			continue
		end
		
		for _, value in array do
			table.insert(newArray, value)
		end
	end

	return newArray
end

local tbl1 = { 1, 2 }
local tbl2 = { 3, 4 }

local combinedArray = CombineArrays(tbl1, tbl2)

print(combinedArray)

However, this is only useful if you plan on using the new table multiple times, also this only works on arrays not dictionary.

I’m pretty sure this will work:

local rice = {1,5}
local pie = {8,6}
for i, v in pairs(table.move(rice, 1, #rice, #pie+1, pie)) do
    print(v)
end

Here we use table.move to combine the two arrays into one. The original value of pie will come first then all the values of rice will come after in the original order (at least for arrays; not sure if this works with dicts)

2 Likes