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

最新文章

  1. Android 笔记 AutoCompleteTextView day8
  2. Linux进程管理
  3. sql自带函数语句
  4. 连续最短路算法(Successive Shortest Path)(最小费用最大流)
  5. ServiceStack.OrmLite 笔记10-group having 分页orderby等
  6. 启动、关闭Service
  7. mysql 存储过程 事务处理
  8. 学习validate
  9. BZOJ 1827: [Usaco2010 Mar]gather 奶牛大集会( dp + dfs )
  10. 2333: [SCOI2011]棘手的操作[写不出来]
  11. Maven使用本地jar包(两种方式)
  12. ASP.NET Core中使用GraphQL - 第六章 使用EF Core作为持久化仓储
  13. GT-随身调详细教程
  14. sitecore 获取item的URL
  15. 来,看看MySQL 5.6, 5.7, 8.0的新特性
  16. redis(四)
  17. java代码操作solr搜索引擎的增删查改
  18. java 虚拟机设置 Xms Xmx PermSize MaxPermSize
  19. 吴裕雄 python 机器学习-NBYS(2)
  20. spring注解方式 idea报could not autowire

热门文章

  1. 华东交通大学2016年ACM“双基”程序设计竞赛 1008
  2. 【Python】我的Python学习笔记【1】【using Python 2】
  3. System & Runtime &Math
  4. 15.Linux安装DHCP服务为虚拟机分配IP
  5. php上传绕过
  6. C语言面试题(二)
  7. linux命令:mkdir命令
  8. 调度系统任务创建---Git部署项目(一)
  9. HDU-4525 威威猫系列故事——吃鸡腿
  10. angular 三目运算符 需要换色或style