lualua-tablemetatable

Why does an error pop up after trying to append?


table1 = {1,2,3,4,5}
table2 = {1,2,3,4}
metatable ={__add = function(table,otherTable)
    sumTable = {}
    for i=1, #table do
     table.insert(sumTable,table[i])
    end
    for i=1, #otherTable do
     table.insert(sumTable,otherTable[i])
    end
    return sumTable
end
}
setmetatable(table1,metatable)

table1 = table1 + table2

this error pops up after runnning the program

lua: [string ""]:6: attempt to call field 'insert' (a nil value) stack traceback: [string ""]:6: in function <[string ""]:3> [string ""]:16: in main chunk


Solution

  • Your code for __add uses table as a parameter which is shadowing the table library. Rename the parameter to something else.