Advertisement
Guest User

Untitled

a guest
Feb 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. tree = {
  2. ['a'] = {'x', 'xx'},
  3. ['b'] = {'y', 'yy'},
  4. ['c'] = {'z', 'zz'}
  5. }
  6.  
  7. function deep_next(tbl, cursor, parent_struct)
  8. local _parent_struct = parent_struct or {}
  9.  
  10. -- if cursor is at a not empty table, continue inside that
  11. if type(tbl[cursor]) == 'table' and next(tbl[cursor]) ~= nil then
  12. table.insert(_parent_struct {tbl, cursor})
  13. return tbl[cursor], next(tbl[cursor]), _parent_struct
  14.  
  15. -- otherwise, if return next() if it is not nil
  16. elseif next(tbl, cursor) ~= nil then
  17. return next(tbl, cursor), tbl, _parent_struct
  18.  
  19. -- if next() is nil, traverse back on parent chain
  20. else
  21. -- if any parent has a not nil next(), return that
  22. while #parent_struct ~= nil do
  23. table.remove(_parent_struct)
  24. local _node = _parent_struct[#_parent_struct]
  25. local _next = next(_node[1][_node[2]])
  26. if _next ~= nil then
  27. return _next, _node[1], _parent_struct
  28. end
  29. end
  30.  
  31. -- otherwise return nil, iteration ends
  32. return nil
  33. end
  34. end
  35. end
  36.  
  37. for k, v in deep_next(), t do
  38. print(k, v)
  39. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement