How do I Insert a Value into a Nested Table?

I got a table that has 2 other tables nested in it. Now I’m trying to insert a value in the 3rd table, how do I do that?

local nestedTable = {
               {
         {}
     }
}
local Value = "hi"
table.insert(nestedTable, Value)
3 Likes

This won’t work:

table.insert()

Requires you to use these arguments:
Argument 1: Table name
Argument 2: Table index (Where you want to place it)
Argument 3: The value

You could use this:

table.insert(nestedTable,#nestedTable+1,Value)
1 Like

Well there seems to be no identifier for the table so you may have to nest-loop or index the multi-dimensional array.

Indexing the Multi-Dimensional Array:

local nestedTable = {
               {
         {}
     }
}
local Value = "hi"
table.insert(nestedTable[1][1], Value) -- index the first table of nestedTable as well as index the first one of that

Nest-Looping towards your goal

local nestedTable = {
               {
         {}
     }
}

local Value = "hi"

for i,v in pairs(nestedTable) do -- loop through the table
      for i, k in pairs(v) do -- nest loop through the value. assuming it's an array.
            table.insert(k, Value)
      end
end

However this can all be simplified with an identifier, either a dictionary or even a variable referencing those nested arrays will do the job.

Edit: tuned up the post a bit.

2 Likes

Assuming its an array you would need to this:

--[[
nestedTable[1] points the first table in nestedTable
nestedTable[1][1] points to the second table in the first table
]]--
table.insert(nestedTable[1][1], Value)
--to test it you can do this:
print(nestedTable[1][1][1]) --will print out hi
6 Likes

Thanks Bro, I did not know the solution was so simple.

2 Likes