This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
LeDark Lua's profile picture

How to merge two tables?

Started by LeDark Lua, 05 August 2015 - 08:45 AM
LeDark Lua #1
Posted 05 August 2015 - 10:45 AM
I want to know how to merge two tables.

local table1={}
local table2={}

function addArgs( ... )
   table1={ ... }
end

function mergeTables( table1, table2 )
   ...
end
??
LeDark Lua #2
Posted 05 August 2015 - 10:54 AM
Ahh noo, i know hoow….
LuckyLuke #3
Posted 06 August 2015 - 09:38 AM
So the solution is? …
LeDark Lua #4
Posted 06 August 2015 - 10:36 AM
You do this:

function mergeTables( t1, t2 )
   for key, value in pairs(t2) do
      t1[ key ] = value
   end
end
LuckyLuke #5
Posted 07 August 2015 - 08:31 AM
Thanks! :)/>
cmdpwnd #6
Posted 08 August 2015 - 03:36 AM
you could have also used table.insert()
Lyqyd #7
Posted 08 August 2015 - 04:13 AM
That would not at all do the same thing.
Astrophylite #8
Posted 08 August 2015 - 01:57 PM
You could use table.insert()


local tEx1 = {"meow"}
local tEx2 = {"woof","cluck"}
function mergeTables(table1, table2)
  for i = 1,#table2 do
    table.insert(table1, #table1+1, table2[i])
  end
end
mergeTables(tEx1, tEx2)
for i = 1,#tEx1 do
  print(tEx1[i])
end
Bomb Bloke #9
Posted 08 August 2015 - 02:01 PM
And what if table2 contains non-numeric keys?
Astrophylite #10
Posted 08 August 2015 - 02:28 PM
And what if table2 contains non-numeric keys?
?
LeDark Lua #11
Posted 08 August 2015 - 02:53 PM
Non-numeric like table has a function or a key named: table1["Hola"]="hello" then the it will ignore it or just throw an error.
Astrophylite #12
Posted 08 August 2015 - 02:54 PM
It won't error, but it won't do anything. Meh, don't use my solution. I never think of that sort of stuff ;)/>
cmdpwnd #13
Posted 09 August 2015 - 10:02 PM
tbl["key"] = 'string'
could still be accessed as
tbl[1] = 'string'
or am I wrong somewhere?
H4X0RZ #14
Posted 10 August 2015 - 12:16 AM
tbl["key"] = 'string'
could still be accessed as
tbl[1] = 'string'
or am I wrong somewhere?

Nope. They are two completely different things.