理解Lua中的__index和__newindex
更新時(shí)間:2015年04月22日 11:17:00 投稿:junjie
這篇文章主要介紹了理解Lua中的__index和__newindex,本文給出了三段代碼來(lái)講解__index和__newindex,代碼中包含詳細(xì)注釋,需要的朋友可以參考下
復(fù)制代碼 代碼如下:
--example:
local temp_table ={
10,
1,
Index1 = "hello",
Index2 = "world",
Index3 = "lua",
Index4 = "language",
lang = "lua language",
}
temp_table.__add = function(a, b) return 3 end
for _, Value in pairs(temp_table) do
print(Value)
end
local temp_metable_table = {
Index1 = "temp_new_metable_Index1",
Index2 = "temp_new_metable_Index2",
Key = "temp_new_metable_Key_end",
}
for _, Metable_Value in pairs(temp_metable_table) do
print(Metable_Value)
end
--只能訪問(wèn)temp_table的方法
--setmetatable(temp_metable_table, temp_table) --如果setmetable 為這種方式的話,那么我不能夠?qū)etable進(jìn)行原子操作
--print(temp_metable_table + temp_table)
--如果是這種方式的話,我們只能訪問(wèn)它的原子,也就是它的數(shù)據(jù)成員
--[[setmetatable(temp_metable_table, {__index = temp_table} )
print(temp_metable_table[1])
print(temp_metable_table["lang"])--]]
--如果是__newindex的話,我們可以訪問(wèn)原table,找到相關(guān)的key,除此之外,你還可以自己給原table添加數(shù)據(jù)成員
setmetatable(temp_metable_table, {__newindex = temp_table} )
temp_metable_table[5] = 100
print(temp_metable_table[5])
print(temp_table[5])
復(fù)制代碼 代碼如下:
Window = {}
Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,}
Window.mt = {}
function Window.new(o)
setmetatable(o ,Window.mt)
print(getmetatable(o))
print(getmetatable(Window.mt))
return o
end
Window.mt.__index = function (t ,key) //由于__index 給賦予了funcion,一個(gè)匿名函數(shù)
-- body
return 1000
end
w = Window.new({x = 10 ,y = 20})
print(w.a) //在這里雖然沒(méi)有a這個(gè)成員,但是會(huì)默認(rèn)a為_(kāi)_index所綁定的function返回值作為a的值
復(fù)制代碼 代碼如下:
Window = {}
Window.mt = {}
function Window.new(o)
setmetatable(o ,Window.mt)
return o
end
Window.mt.__index = function (t ,key)
return 1000
end
Window.mt.__newindex = function (table ,key ,value)
if key == "wangbin" then
rawset(table ,"wangbin" ,"yes,i am")
end
end
w = Window.new{x = 10 ,y = 20}
w.wangbin = "55"
print(w.wangbin)
總結(jié):
如果在元table中去找相應(yīng)的操作,例如__index,__newindex等,如果有則直接訪問(wèn),如果沒(méi)有就新添加進(jìn)元table中
相關(guān)文章
舉例簡(jiǎn)介L(zhǎng)ua中函數(shù)的基本用法
這篇文章主要介紹了舉例簡(jiǎn)介L(zhǎng)ua中函數(shù)的基本用法,--兩個(gè)橫線開(kāi)始單行的注釋,--[[加上兩個(gè)[和]表示多行的注釋--]],需要的朋友可以參考下2015-07-07
如何使用Vim搭建Lua開(kāi)發(fā)環(huán)境詳解
這篇文章主要給大家介紹了關(guān)于如何使用Vim搭建Lua開(kāi)發(fā)環(huán)境的相關(guān)資料,文中通過(guò)圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
Lua教程(十六):系統(tǒng)庫(kù)(os庫(kù))
這篇文章主要介紹了Lua教程(十六):系統(tǒng)庫(kù)(os庫(kù))本文著重講解了OS庫(kù)中的日期和時(shí)間操作和其他系統(tǒng)調(diào)用兩部份內(nèi)容,需要的朋友可以參考下2015-04-04
實(shí)例講解Lua中pair和ipair的區(qū)別
這篇文章主要介紹了實(shí)例講解Lua中pair和ipair的區(qū)別,本文直接用實(shí)例代碼來(lái)講解pair和ipair的區(qū)別,需要的朋友可以參考下2015-04-04
分析Lua觀察者模式最佳實(shí)踐之構(gòu)建事件分發(fā)系統(tǒng)
當(dāng)對(duì)象間存在一對(duì)多關(guān)系時(shí),則使用觀察者模式(Observer Pattern)。比如,當(dāng)一個(gè)對(duì)象被修改時(shí),則會(huì)自動(dòng)通知依賴(lài)它的對(duì)象。觀察者模式屬于行為型模式2021-06-06

