# [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={=112.06, =232.40, =116.00, =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``````

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 .. "("..y..")", x .. "("..y..")", x .. "("..y..")")``````

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

• deepstrasz

#### Bribe

Code Moderator
Level 44
The encapsulation here needs to be addressed. Do/End blocks, that sort of thing.

• deepstrasz