Lua元方法的使用

来源:互联网 发布:怎么弄网络平台卖东西 编辑:程序博客网 时间:2024/04/28 18:41
Set = {}Set.mt = {}function  Set.new( t )local set = {}setmetatable( set, Set.mt )for _, l in ipairs(t) do set[l] = true endreturn setendfunction Set.union( a, b )if getmetatable( a ) ~= Set.mt or getmetatable( b ) ~= Set.mt thenerror("attempt to add a set with a non-set value",2)endlocal res = Set.new{}for k in pairs(a) do res[k] = true endfor k in pairs(b) do res[k] = true endreturn resendfunction Set.intersection( a, b )local res = Set.new{}for k in  pairs(a) dores[k] = b[k]endreturn resendSet.mt.__le = function( a, b )for k in pairs( a ) doif not b[k] then return false endendreturn trueendSet.mt.__lt = function( a, b )return a <= b and not ( b <= a )endSet.mt.__eq = function( a, b )return a <= b and b <= aendfunction  Set.tostring( set )local s = "{"local sep = ""for e in pairs( set ) dos = s .. sep .. esep = ", "endreturn s .. "}"endfunction  Set.print( s )print( Set.tostring(s))endSet.mt.__add = Set.unionSet.mt.__mul = Set.intersectionSet.__tostring = Set.tostring--算数s1 = Set.new({10,20,30,50})s2 = Set.new({30,1})s3 = s1 + s2s4 = s3 * s2Set.print( s3 )Set.print( s4 )s6 = Set.new({8})s5 = s4 + s6Set.print( s5 )--关系t1 = Set.new{2,4}t2 = Set.new{4,10,2}print( t1 <= t2 )print( t1 < t2 )print( t1 >= t1 )print( t1 > t1 )print( t1 == t1 * t2 )

0 0
原创粉丝点击