1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
| print("*********元表************") print("*********元表概念************")
print("*********设置元表************") meta ={} myTable={}
setmetatable(myTable,meta)
print("*********特定操作************") print("*********特定操作-__tostring************") meta2 ={ __tostring=function (t) return t.name end
} myTable2={ name ="who" }
setmetatable(myTable2,meta2) print(myTable2)
print("*********特定操作-__call************") meta3 ={ __tostring=function (t) return t.name end, __call = function(a,b) print(a) print(b) print"not is me" end
} myTable3={ name ="me " }
setmetatable(myTable3,meta3)
myTable3(1) print("*********特定操作-运算符重载************") meta4 = { __add = function(t1,t2) return t1.age + t2.age end, __sub = function(t1,t2) return t1.age - t2.age end, __mul = function(t1,t2) return t1.age * t2.age end, __div = function(t1,t2) return t1.age / t2.age end, __mod = function(t1,t2) return t1.age % t2.age end, __pow = function(t1,t2) return t1.age ^ t2.age end, __eq = function(t1,t2) return t1.age == t2.age end, __lt = function(t1,t2) return false end, __le = function(t1,t2) return t1.age <= t2.age end, __concat = function(t1,t2) return t1.age .. t2.age end
} myTable4 ={age =1}
myTable5 ={age =2} setmetatable(myTable4,meta4) setmetatable(myTable5,meta4)
print(myTable4 .. myTable5) print(myTable4 < myTable5)
print("*********特定操作-__index和newIndex************") meta6Father = { age =2} meta6Father .__index =meta6Father
meta6 = { }
meta6.__index = meta6
myTable6 ={}
setmetatable(myTable6,meta6) setmetatable(myTable6,meta6Father)
print(getmetatable(myTable6))
print(myTable6.age)
rawget(myTable6,"age") print(rawget(myTable6,"age"))
meta7 = {} meta7.__newindex={} myTable7 ={} setmetatable(myTable7,meta7) myTable7.age =1 print(myTable7.age)
rawset (myTable7,"age",2) print(myTable7.age)
|