-1

I have a table that looks like

{
  a = 1,
  b = 2,
  c = 3,
}

And I'd like to move this table, while retaining all its values, into a sub-table within the existing table, so it looks like:

{
  letters = {
    a = 1,
    b = 2,
    c = 3,
  },
  otherStuff = {}
}

Is there any easy way to do this? Thanks!

Sean
  • 105
  • 6

1 Answers1

3

Simply move over the key-value pairs using pairs, move them to a new table, deleting them from the original table, then set the letters and otherStuff subtable:

local t = {a = 1, b = 2, c = 3}

-- Restructure t
local letters = {}
for k, v in pairs(t) do
    letters[k] = v -- copy to letters table
    t[k] = nil -- delete entry - doing this during iteration is fine in Lua
end
-- now update original table
t.letters = letters
t.otherStuff = {}

that said, why do you have to update the original table, rather than simply constructing a new table {letters = t, otherStuff = {}}? This seems to be an X-Y-problem.

Luatic
  • 8,513
  • 2
  • 13
  • 34