Log In  

I have the following (simplified) code, defining the __concat metamethod on a table and using it to combine two table definitions, overwriting keys when they overlap:

tmeta = {
    __concat = function(orig, new)
        for k,v in pairs(new) do
            orig[k] = v
        end
        return orig
    end
}

t = {
    a=1,
    b=2,
    c=3
}

setmetatable(t, tmeta)

t ..= {b=4, d=5}

print(t.a)
print(t.b)
print(t.c)
print(t.d)

This snippet works completely fine, printing the numbers 1, 4, 3, and 5 as expected. However, having a multi-line table on the right-hand side of the compound operator causes it to break:

t ..= {
    b=4, 
    d=5
}

The following form does work fine as a workaround:

t = t .. {
    b=4, 
    d=5
}

so this overall approach is still possible, but it uses 1 more token than the compound form.

Also, the exact same behavior seems to occur with other metamethods (e.g. __add and the += operator), so this isn't anything specific to the concatenation operator.

P#96757 2021-09-01 03:34

This looks like a duplicate of https://www.lexaloffle.com/bbs/?tid=32670

P#97956 2021-09-29 02:52

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2022-12-09 05:00:48 | 0.005s | Q:8