1

I am interested in inserting a table within a table in lua

mytable1={"apple","banana","grape"}
mytable2={"one","two","three"}

I want to insert mytable2 in position 4 of mytable1... so after the merger it should look somewhat like this

mytable1={"apple","banana","grape",{"one","two","three"}}

So far I tried it this way:

table.insert(mytable1,4,mytable2)
print(mytable[4])

the result is table: 0x900b128 instead of mytable2.. I am quite confused.Please advice me where I am doing wrong and what is the right way to proceed.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
bislinux
  • 193
  • 2
  • 3
  • 12
  • 5
    What about that output do you think is wrong? `print` doesn't print out keys and values of tables it just prints `table: 0xXXXXXXX` which is the id of the table. – Etan Reisner Mar 05 '15 at 14:42

3 Answers3

1

Is possible:

tTable = { "apple", "banana", "grape", {"one", "two", "three"}}
tTable[1]
> apple
tTable[4][1]
> one

Print on table does not return it's values, but the indication that's it is a table and it's address.

Source: table inside table in Lua

Suppose you want to simply display everything in your table:

tTable = { "apple", "banana", "grape", {"one", "two", "three"}}

for k,v in pairs(tTable) do
  if type(k) == "table" then
    for _,i in ipairs(k) do
      print(i)
    end
  else
    print(v)
  end
end
> apple 
> banana
> grape
> one
> two
> three
Community
  • 1
  • 1
codingbunny
  • 3,989
  • 6
  • 29
  • 54
1

this is how printing of a table works. Try out print(mytable1) or print(mytable2) and you see a similar output. You used the correct way of inserting that table. Just try out print(table1[4][1]). it should print "one"

Or to get all values try:

for index, value in ipairs(table1[4]) do
  print(value);
end

this will print "one", "two" and "three"

Ivo
  • 18,659
  • 2
  • 23
  • 35
0

You've done it correctly; You're just making incorrect assumptions about values, variables and print.

mytable2 is a variable name. You generally won't see variable names as strings except if you are debugging.

A table is a value. No value has a name. table.insert adds a value (or value reference) to a table. In this case, the value is a table so a reference to it is added to the table referenced by the mytable1 variable.

print calls tostring on its arguments. tostring on a table value returns what amounts to a unique identifier. print(mytable2) would print the same string as print(mytable1[4]) because both reference the same table.

Tom Blodget
  • 20,260
  • 3
  • 39
  • 72