lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Sorting hash keys isn’t really a meaningful operation because of the
ways hash tables are implemented. What we usually do is to put the
hash keys into an array

local t = {}
t["03:05:30"] = 80
t["04:05:21"] = 40
t["01:03:03"] = 20

local a = {}
for k, v in pairs(t) do
    a[#a+1] = { ["k"] = k, ["v"] = v }
end

table.sort(a, compareTime)

-- because I’m preserving the keys and the values, a table is now
being passed to compareTime()
-- so the following kludge should be added to compareTime()

function compareTime(t1,t2)
    t1 = t1.k -- for the purposes of comparison, extract the key value
    t2 = t2.k
    print("Comparing: "..unpack(t1).."-"..unpack(t2))
...


Vaughan


On 24 February 2010 11:04, Valerio Schiavoni
<valerio.schiavoni@gmail.com> wrote:
>
> Hello,
> can anyone explain me how to sort a table whose keys are strings using a custom sorting function ?
> I've tried this code:   http://codepad.org/QakDRqwX
> It doesn't seem to work (table is not sorted, because the comparator function is not executed).
> The tables i want to sort look more or less like to this :
>
> local t = {}
> t["03:05:30"] = 80
> t["04:05:21"] = 40
> t["01:03:03"] = 20
>
> ...
>
>
> Thanks for any suggestion,
>
> Valerio
>
> PS: i found a note about this corner-case at this url: http://www.wowwiki.com/API_sort  but not on the reference manual..