【发布时间】:2017-09-01 18:58:25
【问题描述】:
我正在处理大量用 Lua 编写的数据文件。大部分都是这样写的,以“电话簿”为例:
data = {
-- First Level - country
USA = {
-- Second level - city
Denver = {
-- Third level - actual entries
{name = 'John', number = '12345'},
-- more entries
},
Washington = {
{name = 'Ann', number = '54321'},
-- more entries
},
-- more cities with entries
},
-- more countries with cities and entries
}
因此,第一级是“国家”,第二级是“城市”这一事实是隐含的,但它使数据更加紧凑。
现在,当实际搜索某些数据时,我想将这些数据作为条目进行迭代包括此分级的隐式信息。
-- Coroutine yielding entries including level data
function corIter(data)
for country,l1 in pairs(data) do
for city,l2 in pairs(l1) do
for _,entry in pairs(l2) do
-- Copy the entry
local out = {}
for k,v in pairs(entry) do
out[k] = v
end
-- Add level properties
out.country = country
out.city = city
coroutine.yield(out)
end
end
end
end
-- Iterate over the entries
local cor = coroutine.create(corIter)
local _, entry = coroutine.resume(cor, data)
while entry do
-- Handle the entry, has 'name', 'number', 'country' and 'city' keys
table.print(entry) -- (custom print function I use)
-- Get the next one
_, entry = coroutine.resume(cor)
end
但我认为这种方法可能不好,因为它使整个线程保持活动状态只是为了以特定方式迭代该死的表。
还有其他“明显”的解决方案吗?关键是性能和易用性。我并不完全需要一个通用的解决方案(对于数据表中任意数量的“级别”),但这一切都像黑客一样。
【问题讨论】:
-
你能举一个你想到的查询的例子吗?