orderedpairs.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. --[[
  2. Ordered table iterator
  3. From http://lua-users.org/wiki/SortedIteration
  4. ]]
  5. function __genOrderedIndex( t )
  6. local orderedIndex = {}
  7. for key in pairs(t) do
  8. table.insert( orderedIndex, key )
  9. end
  10. table.sort( orderedIndex )
  11. return orderedIndex
  12. end
  13. function orderedNext(t, state)
  14. -- Equivalent of the next function, but returns the keys in the alphabetic
  15. -- order. We use a temporary ordered key table that is stored in the
  16. -- table being iterated.
  17. local key = nil
  18. --print("orderedNext: state = "..tostring(state) )
  19. if state == nil then
  20. -- the first time, generate the index
  21. t.__orderedIndex = __genOrderedIndex( t )
  22. key = t.__orderedIndex[1]
  23. else
  24. -- fetch the next value
  25. for i = 1,table.getn(t.__orderedIndex) do
  26. if t.__orderedIndex[i] == state then
  27. key = t.__orderedIndex[i+1]
  28. end
  29. end
  30. end
  31. if key then
  32. return key, t[key]
  33. end
  34. -- no more value to return, cleanup
  35. t.__orderedIndex = nil
  36. return
  37. end
  38. --orderedPairs
  39. return function(t)
  40. -- Equivalent of the pairs() function on tables. Allows to iterate
  41. -- in order
  42. return orderedNext, t, nil
  43. end