获取表中值的键和其中的表

我正在制作一个程序,用于搜索表中的值。如果该值不在该表中,则检查其子表。它将根据顺序返回在表中找到的第一个值。我无法想到如何做到这一点。

这是我函数的一个示例:

local T = {
    ["KeyOne"] = "Val1";
    ["KeyTwo"] = "Val2";
    ["KeyThree"] = {
        ["KeyFour"] = "ValueToLookFor";
    };
    ["KeyFive"] = {
        ["KeySix"] = "ValueToLookFor"; -- 不在另一个索引前面,因此另一个索引获胜。
    };
}

print(SearchTable(T, "ValueToLookFor")) --> "KeyThree.KeyFour"

我尝试将正在搜索和迭代的表的表排序到底部,但似乎没有起作用。 有什么想法可以解决这个问题吗?

点赞
用户12918181
用户12918181

你可以使用递归搜索,但是不能保证键的顺序,因为 lua 表是哈希表。

<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type='application/lua'>

function SearchTable(t, value, prefix)
  for k,v in pairs(t) do
    if type(v) == 'table' then
      local res = SearchTable(v, value, prefix and (prefix .. '.' .. k) or k)
      if res then
        return res
      end
    end
    if v == value then
      return prefix and (prefix .. '.' .. k) or k
    end
  end
end

local T = {
    ["KeyOne"] = "Val1";
    ["KeyTwo"] = "Val2";
    ["KeyThree"] = {
        ["KeyFour"] = "ValueToLookFor";
    };
    ["KeyFive"] = {
        ["KeySix"] = "ValueToLookFor"; -- Not ahead of the other index so the other index wins.
    };
}

print(SearchTable(T, "ValueToLookFor"))

</script>

如果你想要有序搜索(例如按名称),你需要在函数开头编写额外的代码,在官方文档中有例子:https://www.lua.org/pil/19.3.html

2020-11-14 20:19:00
用户3342050
用户3342050
#! /usr/bin/env lua

local T = {
    ['KeyOne'] = 'Val1',
    ['KeyTwo'] = 'Val2',
    ['KeyThree'] = {
        ['KeyFour'] = { [1] = 'SomeOtherValue', [2] = 'ValueToLookFor' }
    },
    ['KeyFive'] = {
        ['KeySix'] = { [1] = 'Value', [2] = 'OtherValue' }
    },
}

local function locatePath( tab, value )
    local path = ''  --  占位符
    for key, val in pairs( tab ) do

        if tab[key] == value then  --  找到路径
            return path ..key  --  连接路径

        elseif type( tab[key] ) == 'table' then  --  继续查找
            local found = locatePath( tab[key], value )

            if found ~= '' then  --  找到相关路径
                return path ..key ..'.' ..found  --  连接路径

            end  --  找到
        end  --  递归
    end  --  遍历
    return path
end  --  函数

print( locatePath( T, 'ValueToLookFor' ) )  --  输出 KeyThree.KeyFour.2
2020-11-14 20:57:49