Looping through tables

Consider the table
[lua]
table = {}
table.F = “eff”
table.J = “jay”
table.Y = “why”
table.X = “exx”
[/lua]

when I am looping through a table similar to this it seems that the order they are being looped through is somewhat random.

So my question is, is there any way to loop through a table with the values being returned as they are presented? If that makes any sort of sense…

I suggest you look at the problem different.

Just assign the table content with string keys.

If you loop through the table using “for” the key values can be converted to strings.



for k, v in pairs( table ) do
     print( k )
end


I don’t understand what you mean by assigning the table content with string keys.

You can’t be sure that a lua table’s keys are put in the order you put them in, if you REALLY want them in that order, create a lookup table where you got number keys which point to the other table’s string keys.
[lua]
local MyTbl = {}
MyTbl[“K”] = “blabla”
MyTbl[“I”] = “Duhuuh”

local MyLookupTbl = { “K”, “I” }
[/lua]
Then when you’re looping, you loop through the lookup table, and gets the real table’s key from the value you get.

for k,v in SortedPairs( table ) do

for k,v in ipairs(table)do

ipairs does them in order. It takes about a millisecond longer to run though so it’s not always useful if you don’t need it.

He wants them to be in the order they are presented, not sorted alphabetically.

  • snip -