码迷,mamicode.com
首页 > 其他好文 > 详细

lua 元表

时间:2016-09-24 01:56:17      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Set = {}
Set.mt = {}
function Set.new(t)
    local set = {}
    setmetatable(set, Set.mt)
    for _, l in ipairs(t) do set[l] = 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

function Set.tostring (set)
    local s = "{"
    local sep = ""
    for e in pairs(set) do
        s = s .. sep .. e
        sep = ", "
    end
    return s .. "}"
end

function Set.print (s)
    print(Set.tostring(s))
end

s1 = Set.new{10, 20, 30, 50}
s2 = Set.new{30, 1}

print(getmetatable(s1))
print(getmetatable(s2))

Set.mt.__add = Set.union
s3 = s1 + s2
Set.print(s3)

 

lua 元表

标签:

原文地址:http://www.cnblogs.com/zzyoucan/p/5902157.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!