- __index元方法 (用于检索)
window = {}
window.prototype = { x = 0 , y = 0 , width = 100 , height = 100 }
window.mt = {}
function window.new(o)
setmetatable( o , window.mt )
return o
end
window.mt.__index = window.prototype
w = window.new{ x = 10 , y = 20 }
print(w.width)
print(w.x)
print(w.xxxx)
- __newindex 元方法 (用于更新)
local key = {}
local mt = { __index = function(t) return t[key] end }
function setDefault( t , d )
t[key] = d
setmetatable( t , mt )
end
tab = { x = 10 , y = 20 }
print( tab.x , tab.z )
setDefault( tab , 100 )
print( tab.x , tab.z )
- 定义一个只读的 table
function readonly(t)
local proxy = {}
local mt = {
__index = t ,
__newindex = function( t , k , v)
error("attempt to update a read-only table" , 2 )
end
}
setmetatable(proxy , mt)
return proxy
end
days = readonly{"Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Sataurday" }
print(days[1])