Lua:表作为另一个表的键的树

时间:2017-04-23 09:14:52

标签: lua

我真的需要这样的东西,但无法通过互联网找到如何做到这一点。我有值表,第一个应该变成另一个表的键,但第二个值应该是先前值的键,依此类推。如果硬编码,它将如下所示:

tab["key1"]["key2"] = 123
tab["key1"]["key3"] = 234
print(tab.key1.key2) ---> 123
print(tab.key1.key3) ---> 234

然而,我有动态的按键表,我不知道当我想要这个按键树时它会是什么样子。我想要的解决方案可以让我在树的中间添加新的分支,例如:

tab1 = {"town", "home", 1, "cake"}
value = 1.032
tab2 = {}

要解决的示例:

我有什么:

print(tab2.town.home.1.cake) ---> 1.032

我想要的是什么:

services:
acme.marketing.api.normalizer.subscription:
    class: acme\MarketingBundle\Normalizer\SubscriptionNormalizer
    arguments: ['@acme.marketing.api.normalizer.subscriber']
    public: false
    tags:
        - { name: serializer.normalizer }
acme.marketing.api.normalizer.subscriber:
    class: acme\MarketingBundle\Normalizer\SubscriberNormalizer
    public: false
    tags:
        - { name: serializer.normalizer }

1 个答案:

答案 0 :(得分:1)

local function read_nested_keys(tbl, keys)
   for _, k in ipairs(keys) do
      tbl = tbl[k]
      if tbl == nil then
         break
      end
   end
   return tbl
end

local function write_nested_keys(value, tbl, keys)
   local prev_tbl, last_k
   for _, k in ipairs(keys) do
      last_k, prev_tbl, tbl = k, tbl, tbl[k]
      if tbl == nil then
         tbl = {}
         prev_tbl[k] = tbl
      end
   end
   prev_tbl[last_k] = value
end

示例:

local keys = {"town", "home", 1, "cake"}
local value = 1.032
local root = {}

print(read_nested_keys(root, keys)) ---> nil

write_nested_keys(value, root, keys)

print(root.town.home[1].cake)       ---> 1.032
print(read_nested_keys(root, keys)) ---> 1.032