Lua:使用冒号函数传递表

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

function main()
    test = {1,2}

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

--检查一个元素是否在一个表格中
function table:inTable(element)

    --遍历表格的每个元素
    for i in pairs(self) do
        --如果当前正在检查的元素与搜索字符串匹配,则表格包含该元素
        if self[i] == element then
            return true
        end
   end

    --如果我们已经遍历了整个列表并且没有找到匹配项,则该表格不包含该元素
    return false
end

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

点赞
用户501459
用户501459

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

换句话说,你不能像那样为所有表添加方法。你可以做到的最接近的方法是编写一个函数,它可以将你新构造的所有表都通过一个元表来添加:

--TableMT 元表
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) -- t or {} 如果t为空则返回一个空表。
end

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

    if test:inTable(1) then
        print("working")
    else
        print("not working")
    end
end
2015-07-15 16:48:32