How to split a Lua table containing sub-tables

How can I split a Lua table containing several subcategories into two tables without changing the original table.

eg. divide tbl = {{tbl1}, {tbl2}, {tbl3}, {tbl4}} by subtbl1 = {{tbl1}, {tbl2}} , subtbl2 = {{tbl3}, {tbl4}} , keeping tbl unchanged.

The string has string.sub , but does not know if the table has something like that. I don't think unpack works for my case, also table.remove will change the original tbl .

Adding additional information for my real case:

tbl populated with sub-tables at runtime and the number of sub-tables changes. I want to save the first 2 sub-tables for something and pass the rest of the sub-tables (in the same table) to the function.

+5
source share
2 answers

You can save the first two sub tables using the proposed lhf method. You could then unpack rest of the subtable.

 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') 
+6
source

Try the following:

 subtbl1 = { tbl[1], tbl[2] } subtbl2 = { tbl[3], tbl[4] } 
+2
source

Source: https://habr.com/ru/post/1210747/


All Articles