# Flip Table So Last Is First

I am trying to flip the order of a table so the values are changed as shown below. I have tried the table.sort methods but it doesn’t seem to effect the table at all.

[lua]
local Numbers = { 1, 2, 3 }
[/lua]

Ends With:
[lua]
local Numbers = { 3, 2, 1 }
[/lua]

You need to supply a custom sorting function:

[lua]table.sort( Numbers, function( a, b ) return a > b; end );[/lua]

Yea I saw that on the wiki but it doesn’t seem to work, I think it is because the table containts numbers and not letters but I am not sure.

It will work if the table’s keys are numerical and the values can be compared.

You could do this recursively too.
[lua]local Numbers = { 1, 2, 3, “hai”, “wat” }

function ReverseTable(aTable, aCount, aReversedTable)
if (aCount == nil) then
aCount = 0
aReversedTable = {}
end

``````if (#aTable &gt;= aCount) then
ReverseTable(aTable, aCount + 1, aReversedTable)
table.insert(aReversedTable, aTable[aCount])
end

return aReversedTable
``````

end

for k,v in pairs(ReverseTable(Numbers)) do
print(k, v)
end

– Prints out
– 1 wat
– 2 hai
– 3 3
– 4 2
– 5 1
[/lua]

Thanks for the reply Rob, I have figured out how to do it in the sql query, I will keep you post in mind though for other ordering functions.