Lua: 将表值移入子表中

huangapple go评论63阅读模式
英文:

Lua: moving table values into a sub table

问题

我有一个类似的表格

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

我想将这个表格移动到现有表格中的一个子表格内,同时保留其所有的值,使其看起来像这样:

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

有没有简单的方法可以实现这个?谢谢!

英文:

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!

答案1

得分: 3

只需使用 pairs 遍历键值对,将它们移动到一个新的表中,并从原始表中删除它们,然后设置 lettersotherStuff 子表:

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

-- 重组表 t
local letters = {}
for k, v in pairs(t) do
    letters[k] = v -- 复制到 letters 表
    t[k] = nil -- 删除条目 - 在 Lua 中进行迭代期间执行此操作是可以的
end
-- 现在更新原始表
t.letters = letters
t.otherStuff = {}

话虽如此,为什么要更新原始表,而不是简单地构建一个新表 {letters = t, otherStuff = {}}?这似乎是一个 X-Y 问题。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月4日 00:26:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629585.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定