将Key

编程入门 行业动态 更新时间:2024-10-10 09:26:18
Key-Value和Value-Key词典存储在一个表中(Storing Key-Value and Value-Key dictionaries in a single table)

这样可以吗:例如:

table = { "Mark", "John", "Paul", "Matt", "Chris", ...}

接着

for k,v in pairs(table) do table[v] = k end

或者我应该创建两个单独的表,每对一个? 哪一个更好的风格?

Would this be okay for example :

table = { "Mark", "John", "Paul", "Matt", "Chris", ...}

and then

for k,v in pairs(table) do table[v] = k end

Or should I create two separate tables, one for each pair? Which one is better style?

最满意答案

对于类似列表的表,其中键是整数而值是其他类似于你的表,使用单个表是一个好主意,特别是在它上面有一些元魔法(参见这个答案 )。

话虽这么说,在这种情况下,你应该使用ipairs迭代它,而不是pairs 。

但是,对于像这样的类地图表,使用两个表更好:

my_table = { foo = "bar", spam = "eggs", chunky = "bacon", }

(因为想象如果你有这个会发生什么...)

my_table = { foo = "bar", bar = "baz", }

For a list-like table where the keys are integers and the values are something else like yours, using a single table is a good idea, especially with a bit of meta-magic on it (see this answer).

That being said, in that case, you should use ipairs to iterate it, not pairs.

For map-like table like this, however, using two tables is better:

my_table = { foo = "bar", spam = "eggs", chunky = "bacon", }

(because imagine what would happen if you had this...)

my_table = { foo = "bar", bar = "baz", }

更多推荐

本文发布于:2023-04-29 01:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1334427.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!