Reputation: 13
The goal is to split a lua table into two separated tables. The expected results are as follows: local t1 = { value="foo" } local t2 = { tex="bar" } From local t = { { value = "foo", tex = "bar" } }
I haven't found a solution for this type of table, as the base table is dynamic and can't be changed. I have tried iterating the table and inserting only the certain items in a new table. but that failed
Upvotes: 0
Views: 2175
Reputation: 1762
If you want to split a table in half you can do something like this:
function SplitInHalf(tbl)
local t1, t2 = {}, {} -- create 2 new tables
local state = true -- to switch between t1 and t2 we will use a variable
for k, v in pairs(tbl) do -- iterating original table
(state and t1 or t2)[k] = v -- depending on the state use t1 or t2 and insert a key in it
state = not state -- inverse state, if true make false, if false make true
end
return t1, t2 -- return new tables
end
Upvotes: 3