local t1 = {Apples=1,Oranges=2}
and local t2 = {Apples=1,Lemons=3}, and combine the missing keys into one table that looks like local t3 = {Apples=1,Oranges=2,Lemons=3}.
Is there any way to do this in Lua?
Thanks in advance :}
The way to do this usually follows the same principle in any language. You just loop through each table, adding a key to a new table if it doesn’t already exist. Now you have a table that contains all k, v pairs.
first time writing Lua code like this in a couple years
local function merge (...)
local newTable = {}
for _, t in pairs({...}) do
for k, v in pairs (t) do
if newTable[k] == nil then
newTable[k] = v
end
end
end
return newTable
end
local t1 = {Apples=1,Oranges=2}
local t2 = {Apples=1,Lemons=3}
local merged = merge(t1, t2)
for k, v in pairs(merged) do
print(k, v)
end