英文:
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
遍历键值对,将它们移动到一个新的表中,并从原始表中删除它们,然后设置 letters
和 otherStuff
子表:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论