"Sorted by key" table iterator


/ Published in: Lua
Save to your folder(s)



Copy this code and paste it in your HTML
  1. -- "Sorted by key" table iterator
  2. -- Extracted from http://www.lua.org/pil/19.3.html
  3.  
  4. function pairsKeySorted(t, f)
  5. local a = {}
  6. for n in pairs(t) do
  7. table.insert(a, n)
  8. end
  9. table.sort(a, f)
  10.  
  11. local i = 0 -- iterator variable
  12. local iter = function () -- iterator function
  13. i = i + 1
  14. if a[i] == nil then
  15. return nil
  16. else
  17. return a[i], t[a[i]]
  18. end
  19. end
  20.  
  21. return iter
  22. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.