One caveat though is that, in this example, keys in a will override keys in b. For instance, if a.test is 32 and b.test is 64, then the code will override the 64 and change it to 32.
If you want to prevent that, you could just throw in a simple condition to see if the key doesn’t exist in b:
for i,v in pairs(a) do
if (b[i] == nil) then
b[i] = v
end
end
Note that explicitly checking for nil is required, since the key could have a false value instead possibly.
Wow thanks so much for all your help folks! I feel like I am learning fast and I couldn’t do that without you all.
I changed my mark of solution to @Crazyman32 answer because, while the original was also correct, his response added some depth about not copying over data inside existing keys.
I know this was a really basic question but perhaps it will server to help someone else sometime.
Id hate to necro, but @Crazyman32’s solution doesn’t seem to work for me and I don’t want to start a dupe topic.
The problem I’m having is whenever I try to “Copy” one table into another, the table remains linked to the other table. Test it for yourself:
The print should print 0 every time if it was truly a new table, but it doesn’t, and NewData just acts as a proxy to set DefaultData
local DefaultData = {
Stored = {
Kills = "0",
Deaths = "0",
OwnedShip = "01|",
OwnedSkin = "01|",
OwnedExhaust = "01|",
OwnedRing = "01|",
OwnedFlares = "01|",
},
Temp = {
Ship = nil,
AB = 0,
Kills = 0,
Deaths = 0
}
}
local RepeatTill = 0
repeat
local NewData = {}
for i,v in pairs(DefaultData) do
NewData[i] = v
end
print(NewData.Temp.AB) -- Observe that this should print 0 if it was a new table
NewData.Temp.AB = 123
RepeatTill = RepeatTill + 1
until RepeatTill == 6