有没有一种非hacky的方法,在给定键的表的情况下更改嵌套表中的值?

所以我正在尝试在给定键的表的情况下更改嵌套表中的值

示例:

local DATA = {
    Storage = {
        Person_id = {
            Money = 0;
            Inventory = {
                Item1 = 0;
            }
        }
    }
}

local function ChangeData(ID, KeyTable, Value, Operation)
    local StorageValue = DATA.Storage[ID].Data;
    for _, Key in ipairs(KeyTable) do
        StorageValue = StorageValue[Key];
    end

    if Operation == "+" then
        StorageValue = StorageValue + Value;
    elseif Operation == "=" then
        StorageValue = Value;
    end
end

ChangeData("person_id", {"Money"}, 5, "="};
ChangeData("person_id", {"Inventory", "Item1"}, 5, "="};

这成功地从嵌套表中获取了值(并更改了变量值),但没有更改嵌套表中的值。

...

唯一修复这个问题的方法(我真的不想这样做)就是硬编码它。 例如:

if Operation == "=" then
   if #KeyTable == 1 then
      DATA.Storage[ID].Data[KeyTable[1]] = Value;
   elseif #KeyTable == 2 then
      DATA.Storage[ID].Data[KeyTable[1]][KeyTable[2]] = Value;
--... and so on

所以我的问题是:**有没有一种非hacky的方法,在给定键的表的情况下更改嵌套表中的值?**

点赞
用户7396148
用户7396148

你可以使用 table.remove 删除表格的最后一个数值,将其保存为你的最后一个键。

然后,你可以将代码大部分保留,只需在操作语句体中添加最后一个键的索引即可。

   local DATA = {
      Storage = {
          Person_id = {
              Money = 0,
              Inventory = {
                  Item1 = 5
              }
          }
      }
  }

  local function ChangeData(ID, KeyTable, Value, Operation)
      local StorageValue = DATA.Storage[ID]
      local LastKey = table.remove(KeyTable)

      for i, Key in ipairs(KeyTable) do
          StorageValue = StorageValue[Key]
      end

      if Operation == "+" then
          StorageValue[LastKey] = StorageValue[LastKey] + Value
      elseif Operation == "=" then
          StorageValue[LastKey] = Value
      end
  end

  ChangeData("Person_id", {"Money"}, 5, "=")
  ChangeData("Person_id", {"Inventory", "Item1"}, 5, "+")

  print(DATA.Storage.Person_id.Money)
  print(DATA.Storage.Person_id.Inventory.Item1)

此外,正如 Egor Skriptunoff 在评论中所述,确保将 next,KeyTable 改为 ipairs(KeyTable),以保证你的键值顺序得到保留。

2020-01-06 21:48:01