Quick Links: Download Gideros Studio | Gideros Documentation | Gideros community chat | DONATE
table sorting — Gideros Forum

table sorting

piepie Member
edited September 2015 in General questions
Hi, maybe I am just tired but I can't get this working:

I'd like to sort a table by value, I thought this would work, but apparently I am missing something.
choices = {
	["apples"]= 1, 
	["flour"] = 3, 
	["milk"]=2, 
	["oranges"]=3
	} 
 
table.sort(choices, function(a, b) return a[1] <= b[1] end)
table.concat(choices, ", ")
I figure my output as something like
choices = {apples, milk, flour, oranges}

what am I doing wrong?

Thank you :)

Comments

  • hgy29hgy29 Maintainer
    Accepted Answer
    Read this: http://www.lua.org/pil/19.3.html

    To my understanding, you can't sort an associative array like this because lua tables have no ordering mechanism (think about hashmaps). However arrays can be sorted, because arrays are tables where each value's key is numerical.

    Since what you want is to get is an array of your table's keys sorted following the associated value in the table, you must:
    1. Extract all keys in your table into an array
    local keys={}
    for k in pairs(choices) do table.insert(keys,k) end
    2. Sort your array of keys along the values in your original table
    table.sort(keys,function (a,b) return choices[a]<choices[b] end)
    Mind the comparison operator, use a strict one eg '<' instead of '<=' or lua sort() may behave strangely, not sure why...

    3. Now your keys arrays is ordered the way you want and you can concat them.
    print(table.concat(keys, ", "))
    Also, have a look at this for another explanation: http://stackoverflow.com/questions/15706270/sort-a-table-in-lua
Sign In or Register to comment.