lua - 获取表中值的键及其内部的表
问题描述
我正在制作一个在表中搜索值的程序。如果该值不在该表中,则它检查其子表。它会根据它的顺序在表中返回第一个找到的值。我无法想象如何做到这一点。
这是我的函数将执行的操作的示例:
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 表是哈希表。
<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
推荐阅读
- mongodb - 在 MongoDb 中创建嵌套聚合集
- javascript - 下拉列表不起作用...未从数据库添加到列表的值以及选择显示输出的值以供显示
- javascript - 颜色选择器组件在 Vuetify 模态中不像在整页上那样工作
- ethereum - 元掩码处理错误
- javascript - 替换当前值后求平均值
- html - Google Analytics - 我可以为不同的页面添加一些唯一标识符吗?
- sql - 正则表达式替换字符串模式
- javascript - 根据反应式编程启动和停止计数器
- docker - 在 Docker 容器中计算时间戳(在 ECS 中运行)并传递给 AWS CLI DynamoDB Put-Item
- r - 如何在折叠其他列时按唯一行值对列求和?