为什么不能使用Set:union()代替Set.union? [英] Why can't I use Set:union() instead of Set.union?

查看:155
本文介绍了为什么不能使用Set:union()代替Set.union?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Lua,我宁愿使用冒号(:)作为方法.不幸的是,它并非在所有地方都能正常工作.查看我的代码:

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

如何在提到的地方使用Set:union()还是在这里不能使用?

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

推荐答案

因为冒号只是用于定义和调用函数的语法糖.如您所读,等效于obj.f(obj),而function A:f()等效于function A.f(self).这就是所有冒号的用途.

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.

在您的示例中,Set:union不属于上述两种用途.确实没有更多内容,但是请随时提出:)

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 :)

这篇关于为什么不能使用Set:union()代替Set.union?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆