2

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
Alex Smoke
  • 619
  • 1
  • 8
  • 18

1 Answers1

4

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]
neoaggelos
  • 632
  • 1
  • 4
  • 18
  • Sorry, that's not clear enough for me. I already have a table created and just need to iterate through it. Can you please explain more? How to call your addNew() function on my table "t" ? – Alex Smoke Sep 08 '15 at 08:42
  • Do you create the table, by adding the 'key-value' pairs by hand? Or do you use something like 'myTable = createATableFromRandomData(data)'?? – neoaggelos Sep 08 '15 at 08:43
  • Just by hand, it's stored in a separate file and I need to iterate through it. – Alex Smoke Sep 08 '15 at 08:57
  • 1
    Ive updated the answer, see if that helps – neoaggelos Sep 08 '15 at 09:07
  • That works well, thank you. Not exactly how I was expecting, because there will be a lot of additional code - my tables are pretty big and with this method they will be twice bigger (tables are generated from third-party app, so there is no chance to change their structure). But thank you anyway, your method works. – Alex Smoke Sep 08 '15 at 10:59
  • I'm glad I helped. Same thing could be done with metatables as well, although it's quite advanced and not worth the fuss. Additionally, myTable and keyTable could actually be the same table, no reason to separate them whatsoever. – neoaggelos Sep 08 '15 at 11:14