How to merge two objects

So, I want to merge two objects like this:

-- Object a
{
	something = 1,
	hmmm = "sauce",
	lol = {
		idk = 1234.0987,
		good = "bad"
	}
}

-- object b
{
	something = 2,
	new = 123.123,
	lol = {
		idk = 9999.8888
	}
}

-- Merge b into a
-- a <-- b

-- Expected output
{
	something = 2, -- this was overriden
	hmmm = "sauce", -- this remains the same as it wasn't in object b
	new = 123.123, -- this was added
	lol = {
		idk = 9999.8888, -- this was also overriden even though being in a branch
		good = "bad" -- this also remians the same
	}
}

That’s it, it would be awesome if there is a native lua method to do this, please let me know :slight_smile:

Hi,
try this

for k,v in pairs(objectb) do objecta[k] = v end
1 Like

Yeah, that wont work for deeply rooted objects like lol.idk which changes, but your code will just override it to the new one.

I think this doesn’t handle subtables?

Try the second answer on this stack question: lua - How to merge two tables overwriting the elements which are in both? - Stack Overflow

EDIT:

function tableMerge(t1, t2)
    for k,v in pairs(t2) do
        if type(v) == "table" then
            if type(t1[k] or false) == "table" then
                tableMerge(t1[k] or {}, t2[k] or {})
            else
                t1[k] = v
            end
        else
            t1[k] = v
        end
    end
    return t1
end
2 Likes

IDK how I missed this! I have been browsing the internet for so long on this, thank you so much for pointing it out :slight_smile: