Inheritance and table.unpack()

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,
}

Try this, my friend.

local Table2 = {
	P1 = 1,
	P2 = 2,
	P3 = 3,
}

for index,element in pairs(Table1) do
    Table2[index] = element;
end

If Table1 is an array then this would overwrite P1, P2, and P3. If that’s the case, I suggest using table.insert instead.

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

Inheritance in lua looks like this:

table1 = {
  P1 = "hi";
  P2 = "bye";
}

table2 = {
  P2 = "cya"
}
setmetatable(table2, {__index = table1})

table2.P1 => hi
table2.P2 => cya

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.