Is there a way to iterate through lua dictionary in order that it's created? [duplicate]

瘦欲@ 提交于 2019-12-11 08:34:27

问题


I need to iterate through Lua dictionary in the order that it's created.

For example:

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

I need:

some : xxx
random : xxx
data : xxx
in : xxx
table : xxx

回答1:


EDIT: 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 

To add a new pair into the table:

-- 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

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

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:

Since A pairs the keys in a manner like

1 - key1
2 - key2
...

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]


来源:https://stackoverflow.com/questions/32451755/is-there-a-way-to-iterate-through-lua-dictionary-in-order-that-its-created

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!