面向对象
元表
metatable={key1=1}
mytable={}
将metatable设置为mytable的元表
setmetatable(mytable,metatable)
print(mytable.key1) ---nil
元方法
查询方法 __index (get)
当表中不存在目标key的时候,通过__index可以在元表中进行查询;当表中存在该目标key的时候,将直接获取,不会执行__index元方法。
metatable.__index=metatable
print(mytable.key1) ---1
mytable.key1=10 --mytable插入新的值10
print(mytable.key1) ---10
print(metatable.key1) ----1
设置方法(修改)__newindex
无法进行查询,只能修改(set),可以通过子表修改元表中的值;可以通过子表向元表中添加新的值
metatable.__newindex=metatable
mytable.key1=10 ---修改元表中的值
mytable.key2=20 ---只向元表中添加新值
print(metatable.key1) ----10
print(metatable.key2) ----20
print(mytable.key2) ----nil
查询方法为函数
metatable.__index=function()
return 123456
end
print(mytable.key1)
设置方法为函数
metatable.__newindex=function(tab,key,val)
print(tab,key,val)
end
mytable.key1=20
输出:0000000007795a0 key1 20
metatable.__newindex=function(tab,key,val)
获取元表
local mtab=getmetatable(tab)
设置元表的值
mtab[key]=val
end
mytable.key1=20
print(metatable.key1) ---20
构成元表关系
metatable={key1="hello",key2=123}
mytable={}
setmetatable(mytable,metatable)
metatable.__index=metatable
print(mytable.key1)
元方法 __add
如果想要添加元方法,需要有元表
metatable = {}
-- 构成元表关系
tab1 = {1,2,3}
setmetatable(tab1,metatable)
-- 添加元方法 __add
metatable.__add = function ( t1, t2 )
for k,v in ipairs(t2) do
table.insert(t1,v)
end
return t1
end
tab2 = {4,5,6}
temp = tab2 + tab1
for i,v in ipairs(temp) do
print(i,v)
end
__mod取余(运算符重载)
metatable={}
metatable.__mod=function(tab,val)
for i,v in ipairs(tab) do
tab[i]=v%val
end
end
tab1={100,112,113}
setmetatable(tab1,metatable)
res=tab1%10
for i,v in ipairs(res) do
print(i,v)
end
...可变参数
function Test(...)
print(...)
endp
tab={key1=10}
function tab:func1()
print(self.key1)
end
tab:fnc1() ---10
tab={key1=10}
function tab:func1()
print(self.key1)
end
mytable={}
setmetatable(mytable,tab)
tab.index=tab
tab:func1() :将tab当参数传进去
面向对象
Person={
Age=0,
Name=""
}
构造函数
function Person.New()
Person.__index=Person
local o={}
setmetatable(o,Person)
return o
end
function Person:Print()
print(self.Name,self.Age)
end
p1=Person.New()
p1.Name="ZhangSan"
p1.Age=20
p2=Person.New()
p2.Name="LiSi"
p2.Age=30
p1:Print();
p2:Print();
--继承
Person={
Age=0,
Name=""
}
function Person.New()
Person.__index=Person
local o={}
setmetatable(o,Person)
return o
end
function Person:Print()
print(self.Name,self.Age)
end
Student=Person.New()
function Student:New()
Student.__index=Student
local o={}
setmetatble(o,Student)
return o
end
function Student:Print()
print(self.Student)
end
s1=Student.New()
s1.Name="LiSi"
s1.Age=30
s1:Print();
类调用静态方法使用'.'
对象调用成员方法使用':'