【问题标题】:How to split a Lua table containing sub-tables如何拆分包含子表的 Lua 表
【发布时间】:2015-03-08 01:07:16
【问题描述】:

如何在不更改原始表的情况下将包含少量子表的 Lua 表拆分为两个表。

例如 将tbl = {{tbl1}, {tbl2}, {tbl3}, {tbl4}} 拆分为subtbl1 = {{tbl1}, {tbl2}}subtbl2 = {{tbl3}, {tbl4}},同时保持tbl 不变。

String 有string.sub,但不知道 table 是否有类似的东西。我不认为unpack 适合我的情况,table.remove 也会改变原来的tbl

为我的真实案例添加更多信息:

tbl 在运行时被子表填满,并且子表的数量发生变化。我想保留前 2 个子表,并将其余的子表(在一个表中)传递给函数。

【问题讨论】:

  • 第二个函数需要一个表(从索引 1 开始)?您希望tbl只包含前两个子表吗?
  • 是的,第二个函数需要一个从索引 1 开始的表。但前两个子表不需要作为表。我只需要从前两个子表中检索信息。

标签: lua lua-table


【解决方案1】:

试试这个:

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

【讨论】:

  • 谢谢,但我的情况比较复杂。我的真实情况是原始 tbl 在运行时充满了子表。目标是将除了前 2 个子表之外的其余子表传递给函数,并且前 2 个子表在其他地方使用,因此原始表在填满后不会被修改。
【解决方案2】:

您可以使用 lhf 建议的方法保留前两个子表。然后您可以unpack 剩余的子表。

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')

【讨论】:

  • unpack 支持开始和结束索引的参数,不需要select。只需unpack(t, 3)
  • @EtanReisner 感谢您的反馈。我已更新我的答案以纳入您的建议。
  • 谢谢你们! {unpack(t, 3)} 非常适合我的情况。
猜你喜欢
  • 2021-10-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多