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

Tho*_*mas 5 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()在上述地方使用或者不能在这里使用?

sbk*_*sbk 14

因为冒号只是用于定义和调用函数的语法糖.正如你所读到obj:f()的那样等同于obj.f(obj)和function A:f()等同于function A.f(self).这就是所有冒号都用的.

在您的示例Set:union中,不属于上述两种用法中的任何一种.它没有更多,但随意问:)