Joining two lists

If have two lists:

local A = { var1 = value1, var2 = value2 };
local B = {foo = ‘bar’};

I was to insert the elements of list A with list B.
Output is this -
local B = {foo = ‘bar’, var1 = value1, var2 = value2}

Note that, there’s no ‘{}’ around the elements of list A when they are added to list B.
How do I go about it?

You can add A directly to B, which might do what you want:

B[#B + 1] = A

or

table.insert(B, A)

I say might do since you literally are adding A (the reference to the table) to B; you’ll see any changes made afterward to the “original”. If that’s a concern you’ll instead want to make a copy, which in this case would go something like:

local new_A = {}

for k, v in pairs(A) do
  new_A[k] = v
end

table.insert(B, new_A)

@StarCrunch
Thanks for the reply. But none of these approaches solve what I’m trying to achieve.

This is the output of your approaches.
{“1”:{var1: value1, var2: value2}, foo: ‘bar’}

Whereas I needed this as the output -
{var1: value1, var2: value2, foo: ‘bar’}

You can accomplish that via pairs loop, e.g.

local A = { var1 = 1, var2 = 2 }
local B = {foo = "bar"}

local function addToTable( target, source )
	for key, value in pairs( source ) do
		target[key] = value
	end
end
addToTable(A,B)

for key, value in pairs( A ) do
	print(key,value)
end
2 Likes

Ah, sorry. I understood the “Output is this” and “Note that…” parts to mean “This is what I’m getting, but this is what I want”.

Hey, thanks a lot!
It worked like a charm.