Advanced

Sorting table iterator

Sorting table iterator
May 14, 2016 04:27PM
I have often used the this sorting iterator instead of Pairs and IPairs.
I have use the one described at http://stackoverflow.com/questions/15706270/sort-a-table-in-lua
You have to add function for the sorting. Often adding a lambda function is appropriate.
Example with finds as it is in the example checker.
It show sorting by the key and by the value. I think those two examples will give enough information to use the iterator in checkers. The lambda function below is function(t,a,c) instead of the more natural function(t,a,b) used on stackoverflow because that b triggerd BB code bold text

Iterating trough a list by key order. In this case is it the same as IPairs but it can be used with any key
for k,v in spairs(finds, function(t,a,c) return c < a end) do
    print(k,v)
end
Iterating trough a list by cache_name in reverse order.
for k,v in spairs(finds, function(t,a,c) return t[c].cache_name < t[a].cache_name end) do
    Print(k,v)
end


The rest of the post is the spairs function copies from stackoverflow but with changed functions names so it works in the checker system
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
        TableSort(keys, function(a,b) return order(t, a, b) end)
    else
        TableSort(keys)
    end

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



Edited 2 time(s). Last edit at 05/15/2016 11:16AM by Target.. (view changes)
Re: Sorting table iterator
June 05, 2016 11:08PM
Very helpful functions! Thanks Target!
Re: Sorting table iterator
April 26, 2020 10:32PM
Target., can you update the example to work with the current version of sandbox (standard table.sort instead of TableSort, pairs instead of Pairs, ...)
Sorry, you do not have permission to post/reply in this forum.