WoW:API sort: Difference between revisions

35 bytes added ,  15 August 2023
m
Move page script moved page API sort to WoW:API sort without leaving a redirect
(Alphabetically sort table function)
m (Move page script moved page API sort to WoW:API sort without leaving a redirect)
 
(2 intermediate revisions by 2 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 41: Line 42:


  function pairsByKeys (t, f)
  function pairsByKeys (t, f)
local a = {}
    local a = {}
for n in pairs(t) do table.insert(a, n) end
    for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
    table.sort(a, f)
local i = 0      -- iterator variable
    local i = 0      -- iterator variable
local iter = function ()  -- iterator function
    local iter = function ()  -- iterator function
i = i + 1
        i = i + 1
if a[i] == nil then return nil
        if a[i] == nil then return nil
else return a[i], t[a[i]]
        else return a[i], t[a[i]]
end
        end
end
      end
return iter
      return iter
  end
  end


Line 57: Line 58:


  for title,value in pairsByKeys(randomtable) do
  for title,value in pairsByKeys(randomtable) do
DEFAULT_CHAT_FRAME:AddMessage(title..", "..value);
    DEFAULT_CHAT_FRAME:AddMessage(title..", "..value);
  end
  end


This will print all the variables in randomtable alphabetically!
This will print all the variables in randomtable alphabetically!
{{LUA}}
Anonymous user