【问题标题】:Lua: Passing a table using a colon functionLua:使用冒号函数传递表格
【发布时间】:2015-07-16 01:20:07
【问题描述】:

我正在尝试创建一个函数来检查一个元素是否已经在一个数组中,但是我在将一个表传递给一个冒号函数时遇到了问题。以下代码给了我错误“尝试调用方法'inTable'(一个零值)”:

function main()
    test = {1,2}

    if test:inTable(1) then
        print("working")
    else
        print("not working")
    end
end

--Checks to see if an element is in a table
function table:inTable(element)

    --Go through each element of the table
    for i in pairs(self) do
        --If the current element we are checking matches the search string, then the table contains the element
        if self[i] == element then
            return true
        end
   end

    --If we've gone through the whole list and haven't found a match, then the table does not contain the element
    return false
end

如果我更改它以便调用“inTable(test, 1)”而不是“test:inTable(1)”并将函数定义更改为“function inTable(self, element)”,则此操作正常。我不确定为什么在这里使用冒号函数不起作用。

【问题讨论】:

  • 我也花了一段时间才理解“test:inTable(1)”和“table.inTable(test, 1)”之间的区别。我已经记录了我分析这种差异的步骤here——也许它会有所帮助。

标签: lua


【解决方案1】:

table 是一个命名空间,而不是应用于所有表实例的元表。

换句话说,您不能向所有表格添加方法。您可以获得的最接近的方法是传递所有新构建的表以添加元表的函数:

local TableMT = {}
TableMT.__index = TableMT
function TableMT:inTable(element)
    for i in pairs(self) do
        if self[i] == element then
            return true
        end
   end
   return false
end
function Table(t)
    return setmetatable(t or {}, TableMT)
end

function main()
    test = Table {1,2}

    if test:inTable(1) then
        print("working")
    else
        print("not working")
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2015-12-26
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2013-01-08
    相关资源
    最近更新 更多