Orderedpairs

Iterates over the key/values in a hash table in an order defined by a key comparison function.
 for k, v in orderedpairs(tab[, comparisonFunc] ) do
Note that this function involves creating and sorting a temporary table.
== Arguments ==
; tab : Table - Table to iterate over
; comparisonFunc : Optional function - Function that, given two keys (ka, kb), returns whether ka should be returned before kb.
== Example ==
Consider a table with mostly random string keys, and values set to 1 for simplicity:
 animals = { aardvark = 1, Eagle = 1, zebra = 1 }
You could use orderedpairs to iterate over the table in order specified by the keys:
 for animal, value in orderedpairs(animals) do
 print(animal)
 end
 -- prints Eagle, aardvark, zebra
Notably, Eagle appears first, as upper-case letters appear before lower-case letters in ASCII. To avoid this, you could supply a case-insensitive comparison function:
 function caseInsensitiveCompare(a, b)
 return a:lower() < b:lower()
 end
 for animal, value in orderedpairs(animals, caseInsensitiveCompare) do
 print(animal)
 end
 -- prints aardvark, Eagle, zebra
== Code ==
 local function orderednext(t, n)
 local key = t[t.__next]
 if not key then return end
 t.__next = t.__next + 1
 return key, t.__source[key]
 end
 function orderedpairs(t, f)
 local keys, kn = {__source = t, __next = 1}, 1
 for k in pairs(t) do
 keys[kn], kn = k, kn + 1
 end
 table.sort(keys, f)
 return orderednext, keys
 end
== See also ==
*