这样可以吗:例如:
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 endOr 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", }更多推荐
发布评论