lua - 如何拆分包含子表的 Lua 表

标签 lua lua-table

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

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

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

为我的真实案例添加更多信息:
tbl在运行时填充了子表,并且子表的数量发生了变化。我想保留前 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')

关于lua - 如何拆分包含子表的 Lua 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27865182/

相关文章:

lua - 检查是否所有陈述都是错误的?

lua - 电晕停止对象被拖出屏幕

lua - 如何将此 PAWN 示例转换为 LUA?

c++ - 如何使用 C API 创建嵌套的 Lua 表

随机表 Corona SDK/Lua

loops - 用于在表中创建变量的 Lua 循环

Lua 模式 - 如何删除字符串中不需要的字符串

c++ - 使用 C++ 访问 Lua 全局表

lua - 如何在 Lua 函数上使用参数

Lua:预期索引,结果为零