Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua add two tables

Tags:

lua

lua-table

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')...

like image 987
darkchampionz Avatar asked Nov 22 '25 09:11

darkchampionz


1 Answers

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.)

like image 200
lhf Avatar answered Nov 24 '25 02:11

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!