# [Lua]Sort

#### ZiBitheWand3r3r

Level 17
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``````

``````local x, y, no = {}, {}, 0