将 table 作为参数传递给 Lua 中的函数

Passing a table as argument to function in Lua

我想通过仅将初始 table 作为参数传递来遍历不同的索引 table。 我目前有这个 table:

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
        }
    }
}

我想做一个递归函数来检查这些 table 中的任何一个名称是否等于某个特定的东西和 return 一个字符串。 递归性在于用我想要的任何数量(或直到某个限制)更新此 table 的想法。 自从我尝试以来,我不明白到底出了什么问题:

for k, v in pairs(table) do
    print(k, v, #v.categories)
end 

它正确打印:

stuff_2 table: 0x10abb0 3
stuff_1 table: 0x10aab8 0

但是当将 table 作为参数传递给下面的函数时,它给出了这个错误:

[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

编辑:问题在于没有忽略在 table 上使用对时,这不仅有 table 类别为 subtable,而且还有一个 table 命名类别,如果忽略它则问题已解决。

您递归到没有 categories 字段的子表。尝试访问它们的 categories 会产生 nil,然后您尝试在其上使用长度运算符。因此你的错误:

  attempt to get length of field 'categories' (a nil value)

如果您无法手动跟踪您的应用程序,请输入更多打印语句或获取行级调试器。