我希望通过只传递初始表作为参数来循环遍历不同索引的表。 目前我有这个表:
local table = {
stuff_1 = {
categories = {},
[1] = {
name = 'wui',
time = 300
}
},
stuff_2 = {
categories = {'stuff_10', 'stuff_11', 'stuff_12'},
stuff_10 = {
categories = {},
[1] = {
name = 'peo',
time = 150
},
[2] = {
name = 'uik',
time = 15
},
[3] = {
name = 'kpk',
time = 1230
},
[4] = {
name = 'aer',
time = 5000
}
},
stuff_11 = {
categories = {},
[1] = {
name = 'juio',
time = 600
}
},
stuff_12 = {
categories = {},
[1] = {
name = 'erq',
time = 980
},
[2] = {
name = 'faf',
time = 8170
}
}
}
我想要创建一个递归函数,检查这些表中的名称是否与某个特定内容相等,并返回一个字符串。 递归的思想在于使用任意数量(或者到达某个限制)更新此表。 我不太明白问题出在哪里,因为当我尝试时:
for k, v in pairs(table) do
print(k, v, #v.categories)
end
它正确地打印出:
stuff_2 table: 0x10abb0 3
stuff_1 table: 0x10aab8 0
但是,将表作为参数传递到以下函数时,会出现此错误:
[string "stdin"]:84: attempt to get length of field 'categories' (a nil value)
功能:
function checkMessage(table)
local i = 1
local message = ""
for k, v in pairs(table) do
if(#v.categories == 0) then
while(v[i]) do
if(v[i].name == 'opd') then
if(v[i].time ~= 0) then
message = "return_1"
else
message = "return_2"
end
end
i = i + 1
end
else
checkMessage(table[k])
end
end
return message
end
编辑:问题在于在对表格使用对时,不仅会有一个带有类别子表的表格,还会有一个名为“类别”的表格。如果忽略了这一点,则问题可以得到解决。