I want Table2 to have the same properties as Table1. I’m having the same problem as this post. It has a solution, but now I don’t how how to use it for my situation.
local Table2 = {
table.unpack(Table1), --Table1 has its own properties
P1 = 1,
P2 = 2,
P3 = 3,
}
P1, P2 and P3 will only get overwritten if those keys exist in Table1 as well. If they don’t, then those keys aren’t getting overwritten. Arrays still use the hash part. An array with an element at position 1 will have an index of 1, which does not equal P1. table.insert does not fly for adding keys to a dictionary.
In OP’s case, if Table1 is an array, then unpack is only returning one element because there’s a comma after the unpack. You’d need to iterate through Table1 and put the keys into Table2 like Crowdsource’s suggestion points out.
A test you can run:
local B = {"foo", "bar", "qaz"}
local A = {P1 = 1, P2 = 2, P3 = 3}
for index, element in ipairs(B) do
A[index] = element
end
for key, value in pairs(A) do
print(key, value)
end
Essentially if something isn’t found(P1) in the descendant(table2) it looks to the ancestor(table1).
Properties can be overwritten or not.
Changing table1 can but doesn’t necessarily change table2
OR
constructor functions
local function makeTable()
local newTable = {}
newTable.P0 = "hehe"
return newTable
end
local table1 = makeTable() --don't add stuff
local table2 = makeTable() --add stuff
changing table1 doesn’t change table2 and vice versa, they are two completely seperate entities.