为什么我不能使用Set:union()而不是Set.union?

时间:2010-09-23 14:56:51

标签: lua call operation

我正在学习Lua,我宁愿使用冒号(:)来学习方法。不幸的是,它无处不在。看我的代码:

Set= {}
local mt= {}
function Set:new(m)
    local set= {}
    setmetatable(set,mt)
    for a,b in pairs (m) do
        set[b]=true
    end
    return set
end

function Set.union(a,b)
    local res=Set:new ({})
    for k in pairs (a) do res[k]=true end
    for k in pairs (b) do res[k]=true end
    return res
end
mt.__add=Set.union   -- why Set:union() is not working here ?

s1=Set:new {22,55,77}
s2=Set:new {2,5,3}
s3=s1+s2

如何在上述地点使用Set:union()或者无法在此处使用?

1 个答案:

答案 0 :(得分:12)

因为冒号只是用于定义和调用函数的语法糖。您可能已阅读obj:f()相当于obj.f(obj)function A:f()相当于function A.f(self)。这就是所有冒号都用的。

在您的示例中,Set:union不属于上述两种用途中的任何一种。其中没有更多内容,但随意问:)

相关问题