lua 元表与元方法示例

时间:2021-02-24 08:20:56

-- 1、检查是否有元表
local t = {1, 2}
print(getmetatable(t))     -- nil
print("----------------------")
-- 2、设置元表
local t = {}
print(getmetatable(t))     -->nil

local t1 = {}
setmetatable(t, t1)
print (getmetatable(t))
assert(getmetatable(t) == t1)
print("----------------------")
-- 3、常用元方法
--[[
__add(a, b) --加法
__sub(a, b) --减法
__mul(a, b) --乘法
__div(a, b) --除法
__mod(a, b) --取模
__pow(a, b) --乘幂
__unm(a) --相反数
__concat(a, b) --连接
__len(a) --长度
__eq(a, b) --相等
__lt(a, b) --小于
__le(a, b) --小于等于
__index(a, b) --索引查询
__newindex(a, b, c) --索引更新(PS:不懂的话,后面会有讲)
__call(a, ...) --执行方法调用
__tostring(a) --字符串输出
__metatable --保护元表
--]]

local tmeta_complext= {}
local TComplex={}
function TComplex.new(a,b)
    tComplex = {a,b}
    setmetatable(tComplex, tmeta_complext)
    return tComplex
end

function TComplex.add(c1,c2)
    tcomplext = {0,0}
    setmetatable(tcomplext, tmeta_complext)
    if c1 and c1[1] and type(c1[1]) == "number" then
        tcomplext[1] = tcomplext[1] + c1[1]
    end
    if c1 and c1[2] and type(c1[2]) == "number" then
        tcomplext[2] = tcomplext[2] + c1[2]
    end
    if c2 and c2[1] and type(c2[1]) == "number" then
        tcomplext[1] = tcomplext[1] + c2[1]
    end
    if c2 and c2[2] and type(c2[2]) == "number" then
        tcomplext[2] = tcomplext[2] + c2[2]
    end
    return tcomplext
end

function TComplex.concat(c1,c2)
    return TComplex.add(c1,c2)
end

function TComplex.tostring(c1)
    return "{" ..c1[1]..","..c1[2].."}"
end

function TComplex.print(t)
    print (TComplex.tostring(t))
end

tmeta_complext.__add = TComplex.add
tmeta_complext.__tostring = TComplex.tostring
tmeta_complext.__index = function(t, k)
    return "hei..hei, not accessiable"
end
tmeta_complext.__newindex = function (t, k, v)
    print("Attempt to update a read-only field.")
end
local t3 = TComplex.new(3,1)
local t4 = TComplex.new(4,1)

t4 = t3 + t4
TComplex.print(t4)
print (t4)
print (TComplex.tostring(t3))
print (t3[1],t3[6])
t3[6] = 7
print (t3[1],t3[6])