Why can't I use Set:union() instead of Set.union?

佐手、 提交于 2019-12-10 14:58:43

问题


I am learning Lua and I would rather use the colon (:) for methods. Unfortunately, it's not working everywhere. See my code:

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

How can I use Set:union() on the mentioned place or is it not possible to use here?


回答1:


Because the colon is syntactic sugar only for defining and calling a function. As you have probably read obj:f() is equivalent to obj.f(obj) and function A:f() is equivalent to function A.f(self). That's all colon is used for.

In your example Set:union doesn't fall into any of the two uses above. There isn't really more into it, but feel free to ask :)



来源:https://stackoverflow.com/questions/3779671/why-cant-i-use-setunion-instead-of-set-union

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!