Skip to content
This repository was archived by the owner on Sep 5, 2024. It is now read-only.

Commit ffbd2a1

Browse files
committed
Add table.flatten
1 parent 68549d4 commit ffbd2a1

1 file changed

Lines changed: 30 additions & 0 deletions

File tree

src/Table.lua

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,3 +286,33 @@ end
286286
function table.min(self)
287287
return math.min(table.unpack(self))
288288
end
289+
290+
--[[
291+
* Flattens the table, removing any other tables inside `self` and inserting the
292+
* values inside those tables.
293+
*
294+
* @since 1.3.1
295+
*
296+
* @param {table} self - The target table
297+
* @param {boolean} [recursive] - Whether inner tables should also
298+
* be flattened; defaults to false
299+
--]]
300+
function table.flatten(self, recursive)
301+
-- I would have liked to use ipairs() here, but since we'll need to skip
302+
-- added indexes, I couldn't =/
303+
for i = 1, #self do
304+
if type(self[i]) == 'table' then
305+
if recursive then
306+
table.flatten(self[i])
307+
end
308+
309+
for j, v in ipairs(self[i]) do
310+
table.insert(self, i + j, v)
311+
end
312+
313+
tableIndex = i
314+
i = i + #self[i] - 1
315+
table.remove(self, tableIndex)
316+
end
317+
end
318+
end

0 commit comments

Comments
 (0)