Posted By

pauloiam on 06/28/10


Tagged

table sort key lua


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


"Sorted by key" table iterator


 / Published in: Lua
 

  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  

You need to login to post a comment.