Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Patrick Hurd
- -- Flattens an arbitrary nesting of arrays
- -- Runs using Lua5.3
- -- March 26, 2017
- -- I first wrote this in Perl, then remembered Perl does automatic
- -- list flattening. Next I started writing it in Golang until I
- -- realized Golang doesn't let you arbitrarily nest arrays.
- -- Lua might be the only language I know which allows arbitray
- -- nesting.
- --[[
- Takes a Lua table as an argument, then recurses on each nested
- table. Returns a flattened Lua table.
- ]]--
- function flatten(array)
- local ret = {}
- for k,v in pairs(array) do
- -- If the element is a nested array
- if type(array[k]) == "table" then
- -- Recurse on nested array
- local flattened = flatten(array[k])
- for i,j in pairs(flattened) do
- table.insert(ret, j)
- end
- else
- table.insert(ret, v)
- end
- end
- return ret
- end
- --[[
- This is just a helper function to format the arrays as they
- appear in memory - with nesting.
- ]]--
- function parsed(array)
- local ret = "{"
- for k,v in pairs(array) do
- -- If the element is a nested array
- if type(array[k]) == "table" then
- -- Recurse on nested array
- local flattened = parsed(array[k])
- ret = ret .. flattened
- else
- ret = ret .. v
- end
- if k < #array then
- ret = ret .. ", "
- end
- end
- ret = ret .. "}"
- return ret
- end
- -- Tests
- test1 = {1, 2, {3, 4, {5}, 6}}
- print("Test 1:")
- print(parsed(test1))
- print(parsed(flatten(test1)))
- print()
- test2 = {{{1, 2}, 3, 4}, 5, 6, {7, 8}, 9, 10}
- print("Test 2:")
- print(parsed(test2))
- print(parsed(flatten(test2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement