我有一个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
如果充分利用循环变量,则不需要那些较长的索引链。您似乎只依赖关键变量,但是实际上,值变量具有所需的大多数信息:
function get_item_description(item_id)
for warehouse_key, warehouse_value in pairs(myWarehouseList) do
for department_key, department_value in pairs(warehouse_value.departments) do
for item_key, item_value in pairs(department_value) do
if item_key == item_id then
print(warehouse_key, department_key, item_value.item_description)
end
end
end
end
end
get_item_description'rjXO./SS'
get_item_description'rjXO./SX'