WoW:API sort: Difference between revisions

1,149 bytes added ,  15 August 2023
m
Move page script moved page API sort to WoW:API sort without leaving a redirect
(Use Lua/Libshortcut template. Change category from "LUA Functions" to "Lua functions".)
m (Move page script moved page API sort to WoW:API sort without leaving a redirect)
 
(6 intermediate revisions by 6 users not shown)
Line 1: Line 1:
{{:Lua/Libshortcut|sort|table.sort}}
{{luaapi}}
From [http://lua-users.org/wiki/TableLibraryTutorial TableLibraryTutorial] of lua-users.org.
From [http://lua-users.org/wiki/TableLibraryTutorial TableLibraryTutorial] of lua-users.org.


  table.sort(table [, comp])
  table.sort(table [, compFunc])
sort(table[, compFunc])


Sort the elements of a table in-place (i.e. alter the table).
Sort the elements of a table in-place (i.e. alter the table).
Line 17: Line 18:
  > = table.concat(t, ", ")  -- only specified size is concatenated as well
  > = table.concat(t, ", ")  -- only specified size is concatenated as well
  2, 3, 5
  2, 3, 5
;''Warning:'' Setting the range of the sort is no longer possible since table.setn is no longer supported (setting n=3 will not set the size of the table to 3) [[User:Yssaril|Yssaril]] 05:31, 23 March 2008 (UTC)


A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to be made. For example, the following behaves the same as no function being supplied:
A comparison function can be provided to customise the element sorting. The comparison function must return a boolean value specifying whether the first argument should be before the second argument in the sequence. The default behaviour is for the < comparison to be made. For example, the following behaves the same as no function being supplied:
Line 31: Line 34:
  5, 4, 3, 2, 1
  5, 4, 3, 2, 1


{{LUA}}
----
;''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 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!
Anonymous user