Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. -- Patrick Hurd
  2. -- Flattens an arbitrary nesting of arrays
  3. -- Runs using Lua5.3
  4. -- March 26, 2017
  5.  
  6. -- I first wrote this in Perl, then remembered Perl does automatic
  7. -- list flattening. Next I started writing it in Golang until I
  8. -- realized Golang doesn't let you arbitrarily nest arrays.
  9. -- Lua might be the only language I know which allows arbitray
  10. -- nesting.
  11.  
  12. --[[
  13. Takes a Lua table as an argument, then recurses on each nested
  14. table. Returns a flattened Lua table.
  15. ]]--
  16. function flatten(array)
  17. local ret = {}
  18. for k,v in pairs(array) do
  19. -- If the element is a nested array
  20. if type(array[k]) == "table" then
  21. -- Recurse on nested array
  22. local flattened = flatten(array[k])
  23. for i,j in pairs(flattened) do
  24. table.insert(ret, j)
  25. end
  26. else
  27. table.insert(ret, v)
  28. end
  29. end
  30. return ret
  31. end
  32.  
  33. --[[
  34. This is just a helper function to format the arrays as they
  35. appear in memory - with nesting.
  36. ]]--
  37. function parsed(array)
  38. local ret = "{"
  39. for k,v in pairs(array) do
  40. -- If the element is a nested array
  41. if type(array[k]) == "table" then
  42. -- Recurse on nested array
  43. local flattened = parsed(array[k])
  44. ret = ret .. flattened
  45. else
  46. ret = ret .. v
  47. end
  48. if k < #array then
  49. ret = ret .. ", "
  50. end
  51. end
  52. ret = ret .. "}"
  53. return ret
  54. end
  55.  
  56. -- Tests
  57. test1 = {1, 2, {3, 4, {5}, 6}}
  58. print("Test 1:")
  59. print(parsed(test1))
  60. print(parsed(flatten(test1)))
  61.  
  62. print()
  63.  
  64. test2 = {{{1, 2}, 3, 4}, 5, 6, {7, 8}, 9, 10}
  65. print("Test 2:")
  66. print(parsed(test2))
  67. print(parsed(flatten(test2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement