[Lua] Sort

Level 17
Joined
Nov 21, 2012
Messages
836
My first try with Lua coding. Suppose we have a table named "t" where keys are player numbers, values: player's score. This snippet allows to sort a table by values, so we are able to catch, let's say, top 3 players. Please note that original table is not changed, it is only read.
It can be used of course to sort other things like units damage for example.
I made this based on the page Programming in Lua : 19.3


Lua:
t={[1]=112.06, [4]=232.40, [8]=116.00, [2]=195.87}
function MaxFirst(a, b) return a > b end -- a>b max value first, a<b min value first (default)

function PairsByValues (t, f)
local a, b = {}, {} -- "a" keeps custom values or player number or handleId (keys), "b" keeps values
for k, v in pairs(t) do
   table.insert(b, v)
    a[v]=k
end
table.sort(b, f)
local i = 0                    -- iterator variable
local iter = function ()   -- iterator function
   i = i + 1
    if b[i] == nil then return nil
       else return a[b[i]], b[i]
    end
end
return iter
end

how to read sorted pairs:
Lua:
local x, y, no = {}, {}, 0
for k, v in PairsByValues(t, MaxFirst) do
   no=no+1
   x[no]=v
   y[no]=k
end
print (x[1] .. "("..y[1]..")", x[2] .. "("..y[2]..")", x[3] .. "("..y[3]..")")

will print:
232.4(4) 195.87(2) 116.0(8)
 
Top