如何合并两个表并覆盖两个表中的元素?
我需要合并两个表,如果给定的项目都在两个表中,则第二个表的内容将覆盖第一个表中的内容。 我看了,但标准库似乎没有提供这个。 我在哪里可以获得这样的功能?
I need to merge two tables, with the contents of the second overwriting contents in the first if a given item is in both. I looked but the standard libraries don't seem to offer this. Where can I get such a function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这是我根据 Doug Currie 的回答得出的结论:
Here's what i came up with based on Doug Currie's answer:
这是深度合并的迭代版本,因为我不喜欢递归的潜在堆栈溢出。
Here's iterative version for deep merge because I don't like potential stack overflows of recursive.
对于数字索引表合并:
For numeric-index table merging:
这不能正常工作吗?
Wouldn't this work properly?
我更喜欢 James 版本,因为它简单,并在我的 utils.lua 中使用它 - 我确实添加了对表类型的检查以进行错误处理。
感谢这个很好的函数,它应该是表类的一部分,因此您可以调用
a:merge(b)
但执行table.merge = function(a, b) ... 对我不起作用。 对于真正的书呆子来说,甚至可以压缩成一个衬垫:)
I preferred James version for its simplicity and use it in my utils.lua - i did add a check for table type for error handling.
Thanks for this nice function which should be part of the table class so you could call
a:merge(b)
but doingtable.merge = function(a, b) ...
did not work for me. Could even be compressed to a one liner for the real nerds :)对于大多数情况,Doug Currie 的答案是最简单的。 如果您需要更强大的表合并,请考虑使用
Penlight 库中的 merge()
方法。Doug Currie's answer is the simplest for most cases. If you need more robust merging of tables, consider using the
merge()
method from the Penlight library.字符串解决方案的关键
key for string solution
扩展这个伟大的答案,https://stackoverflow.com/a/1283399/1570165,我想选择一个(纯)函数式方法如下所示:
Extending this great answer, https://stackoverflow.com/a/1283399/1570165, I would like to go with a (pure) functional approach like this one below:
就像Doug Currie说的,你可以使用他的功能,但是他的方法有问题。 如果
first_table
的k
索引中有内容,该函数将覆盖它。我假设您正在尝试合并这些表,而不是覆盖索引和值。 这就是我的方法,它非常相似,但用于合并表。
此解决方案的唯一问题是索引设置为数字,而不是字符串。 这适用于以数字作为索引的表,对于以字符串作为索引的表,请使用 Doug Currie 的方法。
道格·柯里的方法:
Like Doug Currie said, you can use his function, but there is a problem with his method. If
first_table
has things in it'sk
index, the function will over write it.I'm assuming you're trying to merge these tables, not overwrite index's and value's. So this would be my method, it's very similar but is used for merging tables.
The only problem with this solution is that the index is set as numbers, not as strings. This will work with tables with numbers as the index, and for tables with strings as their index, use Doug Currie's method.
Doug Currie's method: