Alphabetically sort table function
(added comment to the size specific sort that it no longer works in the current version of wow) |
(Alphabetically sort table function) |
||
| Line 36: | Line 36: | ||
;''Notes:'' | ;''Notes:'' | ||
: Sorting tables containing non-numeric keys using a custom comparison function does not work. The function will not get called, and the table will be sorted according to some kind of internal function. | : Sorting tables containing non-numeric keys using a custom comparison function does not work. The function will not get called, and the table will be sorted according to some kind of internal function. | ||
==Sorting by Name== | |||
There is a user-function you can write that will sort a table by name during a for function. | |||
function pairsByKeys (t, f) | |||
local a = {} | |||
for n in pairs(t) do table.insert(a, n) end | |||
table.sort(a, f) | |||
local i = 0 -- iterator variable | |||
local iter = function () -- iterator function | |||
i = i + 1 | |||
if a[i] == nil then return nil | |||
else return a[i], t[a[i]] | |||
end | |||
end | |||
return iter | |||
end | |||
This function will replace the pairs function in a for statement. Example: | |||
for title,value in pairsByKeys(randomtable) do | |||
DEFAULT_CHAT_FRAME:AddMessage(title..", "..value); | |||
end | |||
This will print all the variables in randomtable alphabetically! | |||
{{LUA}} | {{LUA}} | ||