2
x = {1, 2, 3}
y = {4, 5, 6}
z = x + y

I have two tables x and y and just want to create a third one which is just the elements of them two (not sorted). I use the above code in an effort but this gives error input:3: attempt to perform arithmetic on a table value (global 'x')...

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
darkchampionz
  • 1,174
  • 5
  • 24
  • 47
  • 1
    If `x = { 1, 2, 3 }` and `y = { 3, 4, 5 }`, should `z = x + y = { 1, 2, 3, 4, 5}` (no duplicates) or `{ 1, 2, 3, 3, 4, 5 }` (possible duplicates)? – GoojajiGreg Apr 18 '17 at 01:37
  • Possible duplicate of [Concatenation of tables in Lua](http://stackoverflow.com/questions/1410862/concatenation-of-tables-in-lua) – Piglet Apr 18 '17 at 11:53

5 Answers5

7

It seems you want to concatenate the two tables to obtain {1, 2, 3, 4, 5, 6}.

There is no builtin function or operator for that. You can use this code:

z = {}
n = 0
for _,v in ipairs(x) do n=n+1; z[n]=v end
for _,v in ipairs(y) do n=n+1; z[n]=v end

If you want to use the syntax z = x + y, then set an __add metamethod. (But perhaps a __concat metamethod is more adequate for your meaning.)

lhf
  • 70,581
  • 9
  • 108
  • 149
2

As the other answers have mentioned, there is no built-in way of doing this. The simplest way of doing it is to define your own function, as in GoojajiGreg's answer. However, if you really want to use the + operator, you can use an __add metamethod.

local metatable = {
    __add = function (t1, t2)
        local ret = {}
        for i, v in ipairs(t1) do
            table.insert(ret, v)
        end
        for i, v in ipairs(t2) do
            table.insert(ret, v)
        end
        return ret
    end
}

local x = {1, 2, 3}
local y = {4, 5, 6}

setmetatable(x, metatable)
setmetatable(y, metatable)

local z = x + y

for i, v in ipairs(z) do
    print(v)
end

-- Output:
-- 1
-- 2
-- 3
-- 4
-- 5
-- 6
Jack Taylor
  • 5,588
  • 19
  • 35
1

You can set function that will sum tables as __add metamethod in the metatable that should be set for all tables that needs that implicit behavior. See Lua manual section "Metatables and Metamethods" for details.

Vlad
  • 5,450
  • 1
  • 12
  • 19
1

You could define a method to return the union of the tables:

local function union ( a, b )
    local result = {}
    for k,v in pairs ( a ) do
        table.insert( result, v )
    end
    for k,v in pairs ( b ) do
         table.insert( result, v )
    end
    return result
end

This doesn't prevent multiple instances of the same value in the resulting table.

GoojajiGreg
  • 1,133
  • 8
  • 16
1

You can also use table.move to do it:

function extend(t1, t2)
    return table.move(t2, 1, #t2, #t1 + 1, t1)
end

Example usage:

a = {"a", "b"}
b = {"c", "d", "e"}
c = extend(a, b)

After this both a and c contains {"a, "b", "c", "d", "e"}, while b is still {"c", "d", "e"}.

Tyilo
  • 28,998
  • 40
  • 113
  • 198