Lua中编辑具有不确定维度的多维表

我想要能够访问和编辑用户生成的表中的值,这个表可以有任意数量的维度。

比如,对于这个嵌套表:

table = {
    '1',
    {
        '2.1',
        '2.2'
    },
    {
        {
            '3.1.1',
            '3.1.2'
        },
        '3.2'
    },
}

我会有另一个表,它包含所需数据的位置,

loc = {3, 1, 2}

理想情况下,我希望能够访问并编辑表中的值,类似于使用table[3][1][2],但利用loc表,

print(table[loc[1]][loc[2]][loc[3]]) --返回3.1.2
print(table[loc]) --这是类似于采用每个索引成员的表,以便按顺序获取表中的每个元素

我还想能够编辑这个表。

table[loc] = {'3.1.2.1', '3.1.2.2'}

我需要能够编辑全局表,所以不能使用this reddit thread中列出的方法,也尚未找到使用元表的正确方式。感谢您的帮助,谢谢。

原文链接 https://stackoverflow.com/questions/69747122

点赞
stackoverflow用户10953006
stackoverflow用户10953006

我认为你可以为此编写一个额外的函数。

function TreeGetValue(Tree, Location)

  local CorrectTree = true
  local Index       = 1
  local Dimensions  = #Location
  local SubTable    = Tree
  local Value

  --根据location找到最深的表
  while (CorrectTree and (Index < Dimensions)) do
    local IndexedValue = SubTable[Location[Index]]
    if (type(IndexedValue) == "table") then
      SubTable = IndexedValue
      Index    = Index + 1
    else
      CorrectTree = false
    end
  end

  --获取最后一个值,无论其类型如何
  if CorrectTree then
    Value = SubTable[Location[Index]]
  end

  return Value
end

在此处,我们假定树最初的格式是正确的。 如果我们发现任何问题,我们将标志CorrectTree设置为false,以便立即停止。

我们需要确保每个维度都有一个表,以便从中索引值。

> TreeGetValue(table, loc)
3.1.2

显然,编写“set”函数也很容易:

function TreeSetValue (Tree, Location, NewValue)

  local Index      = 1
  local Dimensions = #Location
  local SubTable   = Tree

  --根据location找到最深的表
  while (Index < Dimensions) do
    local IndexedValue = SubTable[Location[Index]]

    --如有需要,创建新的子表
    if (IndexedValue == nil) then
      IndexedValue = {}
      SubTable[Location[Index]] = IndexedValue
    end

    SubTable = IndexedValue
    Index    = Index + 1
  end

  --设置或替换以前的值
  SubTable[Location[Index]] = NewValue
end

然后使用测试数据对其进行测试:

> TreeGetValue(table, loc)
3.1.2
> TreeSetValue(table, loc, "NEW-VALUE")
> TreeGetValue(table, loc)
NEW-VALUE
2021-10-28 01:46:46