1. Post #1
    joyenusi's Avatar
    May 2006
    148 Posts
    Consider the table
    table = {}
    table.F = "eff"
    table.J = "jay"
    table.Y = "why"
    table.X = "exx"
    

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

  2. Post #2
    EthanTheGreat's Avatar
    September 2010
    186 Posts
    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.


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

  3. Post #3
    joyenusi's Avatar
    May 2006
    148 Posts
    I don't understand what you mean by assigning the table content with string keys.

  4. Post #4
    Donkie's Avatar
    July 2009
    1,034 Posts
    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.
    local MyTbl = {}
    MyTbl["K"] = "blabla"
    MyTbl["I"] = "Duhuuh"
    
    local MyLookupTbl = { "K", "I" }
    
    Then when you're looping, you loop through the lookup table, and gets the real table's key from the value you get.
    Reply With Quote Edit / Delete Reply Windows Vista Sweden Show Events Agree Agree x 1Useful Useful x 1 (list)

  5. Post #5
    Gold Banana
    Banana Lord.'s Avatar
    May 2010
    5,274 Posts
    for k,v in SortedPairs( table ) do
    Reply With Quote Edit / Delete Reply Mac United States Show Events Disagree Disagree x 1Agree Agree x 1 (list)

  6. Post #6
    Your local friendly Lua helper!
    bobbleheadbob's Avatar
    July 2011
    184 Posts
    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.

  7. Post #7
    Donkie's Avatar
    July 2009
    1,034 Posts
    He wants them to be in the order they are presented, not sorted alphabetically.

  8. Post #8
    Gold Banana
    Banana Lord.'s Avatar
    May 2010
    5,274 Posts
    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.
    ipairs is deprecated and only works on tables with number indexes