首页 > 解决方案 > 获取表中值的键及其内部的表

问题描述

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

这是我的函数将执行的操作的示例:

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")) --> "KeyThree.KeyFour"

我尝试将表格排序到正在搜索和迭代的表格的底部,但它似乎不起作用。关于如何做到这一点的任何想法?

标签: lua

解决方案


您可以使用递归搜索,但这不能保证键的顺序,因为 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


推荐阅读