【问题标题】:Passing a table as argument to function in Lua将表作为参数传递给 Lua 中的函数
【发布时间】:2015-09-30 04:14:12
【问题描述】:

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

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

编辑:问题在于不要忽略在表上使用对时,这不仅有带有类别子表的表,而且还有一个名为 category 的表,如果忽略此问题,则问题已解决。

【问题讨论】:

  • 如果您发现自己需要在表中搜索名称,那么您最好重组表以将名称作为键而不是值。

标签: function lua arguments lua-table


【解决方案1】:

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

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

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

【讨论】:

  • 问题仍然存在,为什么它们没有类别字段,而表的子表作为参数传递呢?我也可以在函数内打印#v.categories,但不能将其用作条件......嗯?
  • 并非所有子表有都有该字段,并且它在一个没有的子表(例如类别表本身)上失败。看着你的代码,这对我来说是很明显的,但即使你没有通过阅读看到这一点,这也是一些更多的打印语句和/或调试器会为你揭示的东西。
猜你喜欢
  • 1970-01-01
  • 2013-07-13
  • 2012-01-25
  • 2016-11-06
  • 2017-07-11
  • 1970-01-01
  • 2013-01-27
  • 2018-12-15
相关资源
最近更新 更多