【问题标题】:Is there a way to split a table in two in lua?有没有办法在lua中将一个表一分为二?
【发布时间】:2021-02-06 19:14:14
【问题描述】:

目标是将一个 lua 表拆分为两个单独的表。 预期结果如下: 本地 t1 = { value="foo" } 本地 t2 = { tex="bar" } 从 本地 t = { { 价值=“富”, 特克斯=“酒吧” } }

我还没有找到这种类型的表的解决方案,因为基表是动态的并且无法更改。 我尝试迭代表并仅在新表中插入某些项目。但是失败了

【问题讨论】:

    标签: lua


    【解决方案1】:

    如果你想把一张桌子分成两半,你可以这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-06-09
      • 1970-01-01
      • 2014-04-30
      • 2018-11-25
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多