0

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?

1 Answer 1

3

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.