在Lua中将表作为参数传递给函数

3

我希望通过只传递初始表作为参数来循环遍历不同索引的表。 目前我有这个表:

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

编辑:问题在于在对表格使用对时,不仅会有一个带有类别子表的表格,还会有一个名为“类别”的表格。如果忽略了这一点,则问题可以得到解决。


1
如果你发现自己需要在表格中搜索名称,那么最好重新构建你的表格,将名称作为键而不是值。 - lhf
1个回答

4
你正在递归遍历没有“categories”字段的子表。试图在它们上面访问“categories”会返回“nil”,然后你尝试使用长度运算符。因此,你会看到错误:
  attempt to get length of field 'categories' (a nil value)

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

问题仍然存在,为什么它们没有类别字段,而作为参数传递的表的子表却有?我也可以在函数内部打印#v.categories,但不能将其用作条件... 嗯? - SGali
并非所有的子表都有该字段,它在一个没有该字段的子表上失败了(例如类别表本身)。通过查看您的代码,这对我来说非常明显,但即使您没有通过阅读看到它,更多的打印语句和/或调试器也会为您揭示这种情况。 - Mud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接