首先給大家看一段lua創(chuàng)建對(duì)象的代碼
function first:new()
local o={}
setmetatable(o,self)
self.__index=self
return o
end
估計(jì)大家都敲過好多遍了误续,這段代碼的含義就是:創(chuàng)建一個(gè)o育瓜,將自身設(shè)置為o的元表恋脚,然后將自身__index元方法設(shè)置為查找自身,但為什么這么做呢?
還有另外一個(gè)創(chuàng)建對(duì)象的方法
function first:new()
local o={}
setmetatable(o,{__index=self})
return o
end
大家應(yīng)該知道這兩個(gè)創(chuàng)建的結(jié)果是相同的
這個(gè)要從table查詢的方式說起:
當(dāng)訪問一個(gè)table中不存在的字段時(shí),table就會(huì)去查找它元表的__index字段缤剧,所以要找到這個(gè)不存在的字段,是要兩個(gè)條件,首先要有元表李皇,其次元表有__index字段慰丛。所以第一個(gè)案例首先使用setmetatable(o,self)給o設(shè)置一個(gè)元表哪亿,但這時(shí)候去訪問self的字段會(huì)返回nil苏潜,因?yàn)閟elf中沒有__index字段,所以需要定義self.__index=self戳气。
這時(shí)第二個(gè)案例大家應(yīng)該也就理解了巧鸭,setmetatable(o,{__index=self})瓶您,就是將一個(gè)table {__index=self}設(shè)置為o的元表,查詢的時(shí)候o首先找到它的元表{__index=self}纲仍,然后在元表中找到__index字段呀袱,由__index給它帶路,找到了self郑叠。
下面是一些有意思的事例夜赵,幫助理解
local first={a=100,b=200}
local second={a=300,b=400}
function first:new()
local o={}
setmetatable(o,self)
self.__index=second
return o
end
function second:new()
local o={}
setmetatable(o,first)
self.__index=first
return o
end
-- 這里的調(diào)用順序會(huì)有影響哦,先調(diào)用first:new()乡革,然后first.__index才存在哦
local t1=first:new()
local t2=second:new()
print(t1.a)
print(t2.a)
答案是:
300
300
local first={a=100,b=200}
local second={a=300,b=400}
function first:new()
local o={}
setmetatable(o,self)
self.__index=self
return o
end
function second:new()
local o={}
setmetatable(o,first)
first.__index=second
return o
end
-- 可以試一下將t1和t2的賦值順序調(diào)換寇僧,查看結(jié)果
local t1=first:new()
local t2=second:new()
print(t1.a)
print(t2.a)
答案是:
300
300
function second:new()
local o={}
setmetatable(o,{__index={a=55}})
return o
end
local t2=second:new()
print(t2.a)
答案是:
55