我正在学习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 setendfuncti
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()或者不能在这里使用?
因为冒号只是用于定义和调用函数的语法糖.你可能已经读过obj:f()等价于obj.f(obj)和函数A:f()相当于函数A.f(self).这就是所有冒号都用的.在您的示例中Set:union不属于上述两种用法中的任何一种.它没有更多,但随意问:)
