面向对象
metatable ={ key1 =1}
mytable ={}
//将metable设置为mytable的元素, 类似metatable为父类,继承
setmetatable( mytable,metatable)
当表中不存在该目标key时,通过index可以在元表中进行查询 Q1
当表中存在该目标key时,不会去执行__index方法,也就不会去元表中查询 Q2
print(mytable.key1) --nil
metatable.__index = metatable
print(mytable.key1) --1 设置index方法后,Q2执行
mytable.key1 =10 --10 相当于给表新添加建, 但并没有修改元表中的值
print(metatable.key1) --1
不能进行设置,只能get
可以通过子表修改元表中的值
可以通过子表向元表中添加新的值
metatable.__newindex = metatable
mytable.key1 =10 --修改元表中的值
mytable.key2 =20 --添加新的值
print(metatable.key1) --10
print(metatable.key2) --20
print(mytable.key1) --nil
metatable.__index = function ( )
print("没有此键")
end
print(mytable.key1)
不能查询,只能修改
可以通过子表修改元表中的值
可以通过子表向元表中添加新的值
metatable.__newindex = metatable
mytable.key1 =10 --修改元表中的值
mytable.key2 =20 --添加新的值
print(metatable.key1) --10
print(metatable.key2) --20
print(mytable.key1) --nil
metatable.__newindex = function(tab,key,val)
local mtab = getmetatable(tab) --获取元素
mtab[key] = val --设置元素的值
--mtab.key = val --插入新的值
end
mytable.key1 =20
metatable = {}
tab1 ={1,2,3}
setmetatable(tab1,metatable)
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 = tab1+tab2
print(#temp) -- 6 说明添加成功
metatable ={}
metatable.__mod = function(tab,val)
for k,v in ipairs (tab) do
tab[k] = v % val
return tab
end
tab1 ={100,224,36}
setmetatable(tab1,metatable)
res = tab1 %10
for i,v in ipairs (res) do
print(i,v)
end
Bagclass.lua
local BagClass = {Id,Name,Level,Star,Ref}
--构造
function BagClass.New()
local o ={}
BagClass.__index = BagClass
setmetatable(o,BagClass)
return o
end
--成员函数
function BagClass : ToString()
return string,format( "Id:%d,Name:%s,Level:%d,Star: %d, Ref :%s",
self.Id,self.Name,self.Level,Self.Star,self.Ref
)
return BagClass
BagManager.lua
BagClass = require "BagClass"
BagManager = {}
local this = BagManager
BagManager.data = {
{1001,"天刀1",6,3,"这是xxx"},
{1002,"天刀2",5,3,"这是xxx"},
{1003,"天刀3",3,2,"这是xxx"},
{1004,"天刀4",4,2,"这是xxx"},
{1005,"天刀5",4,1,"这是xxx"},
{1006,"天刀6",5,2,"这是xxx"},
}
BagManager.BagDic = {}
-----table.remove(this.BagDic,10)
function BagManger.ParseData()
for i,v in ipairs (this.data) do
local item = BagClass.New()
local index =1
item.Id = v[index]; index = index +1
item.Name = v[index];index = index + 1
item.Level = v[index];index = index + 1
item.Star = v[index];index = index + 1
item.Ref = v[index];index = index + 1
table.insert(this.BagDic,item)
end
end
function BagManager.Sort()
for i=1,#this.BagDic -1 do
for j=1,#this.BagDic -i do
if this.BagDic[j].Level == this.BagDic[j+1].Level then
if this.BagDic[j].Star> this.BagDic[j+1].Star then
this.BagDic[j],this.BagDic[j+1] = this.BagDic[j+1],this.BagDic[j]
-- temp = a; a = b; b = temp
end
else
if this.BagDic[j].Level > this.BagDic[j+1].Level then
this.BagDic[j],this.BagDic[j+1] = this.BagDic[j+1],this.BagDic[j]
end
end
end
end
end
this.ParseDate() -- 调用排序方法
for k,v in ipairs (this.BagDic) do
print(k,v:ToString())
end