有没有一种方法可以遍历lua字典以创建它? [英] Is there a way to iterate through lua dictionary in order that it's created?
问题描述
我需要按照创建它的顺序遍历Lua字典.
I need to iterate through Lua dictionary in the order that it's created.
例如:
t = {
['some'] = 'xxx',
['random'] = 'xxx',
['data'] = 'xxx',
['in'] = 'xxx',
['table'] = 'xxx',
}
成对进行普通迭代会给出随机序列顺序:
Normal iterating with pairs gives a random sequence order:
for key, val in pairs(t) do
print(key.." : "..val)
end
random : xxx
some : xxx
data : xxx
table : xxx
in : xxx
我需要:
some : xxx
random : xxx
data : xxx
in : xxx
table : xxx
推荐答案
更改了答案,下面是旧答案供参考
Changed the answer, the old one is below for reference
-- function definition
function addNewItem(keyTable, myTable, key, value)
table.insert(keyTable, key)
myTable[key] = value
end
要将新对添加到表中:
-- you may need to reset keyTable and myTable before using them
keyTable = { }
myTable = { }
-- to add a new item
addNewItem(keyTable, myTable, "key", "value")
然后,按照添加键的顺序进行迭代:
Then, to iterate in the order the keys were added:
for _, k in ipairs(keyTable) do
print(k, myTable[k])
end
旧答案
您是创建表的人吗(Lua称这些表而不是字典)?如果是这样,您可以尝试执行以下操作:
OLD ANSWER
Are you the one creating the table (Lua calls these tables and not dictionaries)?? If so, you could try something like the following:
-- tmp is a secondary table
function addNew(A, B, key, value)
table.insert(A, key)
B[key] = value
end
-- then, to browse the pairs
for _,key in ipairs(table) do
print(key, B[key])
done
这个想法是您使用两个表.一个握住您添加的键"(A),另一个握住(B)的实际值.他们看起来像这样:
The idea is that you use two tables. One holds the 'keys' you add (A) and the other (B) the actual values. They look like this:
由于A以类似的方式配对密钥
Since A pairs the keys in a manner like
1 - key1
2 - key2
...
然后,ipairs(A)将始终按添加键的顺序返回键.然后 使用这些键访问数据
Then ipairs(A) will always return the keys in the order you added them. Then use these keys to access the data
data = B[key1]
这篇关于有没有一种方法可以遍历lua字典以创建它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!