How to split a Lua table containing sub-tables
snippet in lua

How to split a Lua table containing sub-tables

user3440

local unpack = table.unpack or unpack

local t = { {1}, {2}, {3}, {4}, {5}, {6} }

local t1 = { t[1], t[2] }    -- keep the first two subtables
local t2 = { unpack(t, 3) }  -- unpack the rest into a new table

-- check that t has been split into two sub-tables leaving the original unchanged
assert(#t == 6, 't has been modified')

-- t1 contains the first two sub-tables of t
assert(#t1 == 2, 'invalid table1 length')
assert(t[1] == t1[1], 'table1 mismatch at index 1')
assert(t[2] == t1[2], 'table1 mismatch at index 2')

-- t2 contains the remaining sub-tables in t
assert(#t2 == 4, 'invalid table2 length')
assert(t[3] == t2[1], 'table2 mismatch at index 1')
assert(t[4] == t2[2], 'table2 mismatch at index 2')
assert(t[5] == t2[3], 'table2 mismatch at index 3')
assert(t[6] == t2[4], 'table2 mismatch at index 4')