【发布时间】:2020-01-29 06:17:23
【问题描述】:
- 我是 Lua 的新手(就像昨天的新手一样),所以请多多包涵...
- 对于这个问题的复杂性,我深表歉意,但我不知道如何证明我正在尝试做的事情:
我有一个 Lua 表被用作字典。元组(?)没有数字索引,但主要使用字符串索引。许多索引实际上与包含更详细信息的子表相关,并且这些表中的一些索引与更多表相关 - 其中一些深度为三或四个“级别”。
我需要创建一个函数,该函数可以从多个“级别”中搜索特定项目描述到字典的结构中,而无需提前知道哪些键/子键/子子键引导我找到它。我曾尝试使用变量和for 循环来执行此操作,但遇到了一个问题,即使用这些变量动态测试一行中的两个键。
在下面的示例中,我试图获取值:
myWarehouselist.Warehouse_North.departments.department_one["rjXO./SS"].item_description
但由于我事先不知道我正在查看“Warehouse_North”还是“department_one”,所以我使用变量遍历这些备选方案,搜索特定的项目 ID“rjXO./SS”,所以对该值的引用最终看起来像这样:
myWarehouseList[warehouse_key].departments[department_key][myItemID]...?
基本上,我遇到的问题是当我需要将两个变量背靠背放置在存储在字典第 N 级的值的引用链中时。我似乎无法将其写成 [x][y],或 [x[y]],或 [xy] 或 [x]。[y]...我明白在 Lua 中,xy与 x[y] 不同(前者直接通过字符串索引“y”引用键,而后者使用存储在变量“y”中的值,可以是任何值。)
我尝试了许多不同的方法,但都得到了错误。
有趣的是,如果我使用完全相同的方法,但在字典中添加一个具有常量值的附加“级别”,例如 ["items"](在每个特定部门下),它允许我引用值没有问题,我的脚本运行良好...
myWarehouseList[warehouse_key].departments[department_key].items[item_key].item_description
Lua 语法应该是这样的吗?我已经更改了表格结构,在每个部门下都包含了额外的“项目”层,但这似乎是多余和不必要的。是否可以进行语法更改以允许我在 Lua 表值引用链中背靠背使用两个变量?
提前感谢您的帮助!
myWarehouseList = {
["Warehouse_North"] = {
["description"] = "The northern warehouse"
,["departments"] = {
["department_one"] = {
["rjXO./SS"] = {
["item_description"] = "A description of item 'rjXO./SS'"
}
}
}
}
,["Warehouse_South"] = {
["description"] = "The southern warehouse"
,["departments"] = {
["department_one"] = {
["rjXO./SX"] = {
["item_description"] = "A description of item 'rjXO./SX'"
}
}
}
}
}
function get_item_description(item_id)
myItemID = item_id
for warehouse_key, warehouse_value in pairs(myWarehouseList) do
for department_key, department_value in pairs(myWarehouseList[warehouse_key].departments) do
for item_key, item_value in pairs(myWarehouseList[warehouse_key].departments[department_key]) do
if item_key == myItemID
then
print(myWarehouseList[warehouse_key].departments[department_key]...?)
-- [department_key[item_key]].item_description?
-- If I had another level above "department_X", with a constant key, I could do it like this:
-- print(
-- "\n\t" .. "Item ID " .. item_key .. " was found in warehouse '" .. warehouse_key .. "'" ..
-- "\n\t" .. "In the department: '" .. dapartment_key .. "'" ..
-- "\n\t" .. "With the description: '" .. myWarehouseList[warehouse_key].departments[department_key].items[item_key].item_description .. "'")
-- but without that extra, constant "level", I can't figure it out :)
else
end
end
end
end
end
【问题讨论】:
标签: dictionary for-loop lua lua-table