2

I am very new to Lua, so please be gentle.

I want a sorted results based on the "error" key. For this example, the output should be:

c  50   70
d  25   50
b  30   40
a  10   20 

Here is my script:

records = {}

records["a"] = {["count"] = 10, ["error"] = 20}
records["b"] = {["count"] = 30, ["error"] = 40}
records["c"] = {["count"] = 50, ["error"] = 70}
records["d"] = {["count"] = 25, ["error"] = 50}

function spairs(t, order)
    -- collect the keys
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end

    -- if order function given, sort by it by passing the table and keys a, b,
    -- otherwise just sort the keys
    if order then
        table.sort(keys, function(a,b) return order(t, a, b) end)
    else
        table.sort(keys)
    end

    -- return the iterator function
    local i = 0
    return function()
        i = i + 1
        if keys[i] then
            return keys[i], t[keys[i]]
        end
    end
end

for k, v in pairs(records) do
    for m, n in pairs(v) do
        for x, y in spairs(v, function(t,a,b) return t[b] < t[a] end) do
            line = string.format("%s %5s   %-10d", k, n, y)
        end
    end
    print(line)

end

I found this about sorting a table and tried to implement it. But it does not work, results are not sorted.

1 Answer 1

1

table.sort only works when the table elements are integrally indexed. In your case; when you try to call spairs, you are actually calling table.sort on the count and error indices.

First off; remove the ugly, irrelevant nested for..pairs loops. You only need the spairs for your task.

for x, y in spairs(records, function(t, a, b) return t[b].error < t[a].error end) do
    print( x, y.count, y.error)
end

And that is all.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.