Search code examples
lualua-table

Add all elements from a table to another table in lua


In javascript you can do the following

const obj1 = {a:1, b:'blue', c:true};
const obj2 = {...obj1, d:3, e:'something else'};

and you object 2 will have all of obj 1 in it.

Is there a way to do this in lua?


Solution

  • You'd have to write your own function for this purpose:

    local function add_missing(dst, src)
        for k, v in pairs(src) do
            if dst[k] == nil then
               dst[k] = v
            end
        end
        return dst -- for convenience (chaining)
    end
    

    which you may then use as follows:

    local obj1 <const> = {a = 1, b = 'blue', c = true}
    local obj2 <const> = add_missing({d = 3, e = 'something else'}, {a = 1, b = 'blue', c = true})
    

    Note: JavaScript's spread operator also guarantees a certain order of execution; that is, in your example fields from obj2 would override those from obj1, which is why I've included an explicit nil check to only include missing fields:

    > {...{a: 2}, a: 1}
    { a: 1 }
    > {a: 1, ...{a: 2}}
    { a: 2 }