首页 > 解决方案 > 在给定键表的情况下,是否有一种简单的方法来更改嵌套表中的值?

问题描述

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

例子:

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

所以我要问的是:在给定键表的情况下,是否有一种简单的方法来更改嵌套表中的值?

标签: lualua-table

解决方案


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

然后,您可以按原样使用您的代码,只需将最后一个键索引添加到您的操作 if 语句体中。

   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, KeyTableipairs(KeyTable)以确保保留您的密钥顺序。


推荐阅读