分类:
版权声明:本文为博主原创文章,未经博主允许不得转载。
- --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
- --只能访问temp_table的方法
- --setmetatable(temp_metable_table, temp_table) --如果setmetable 为这种方式的话,那么我不能够对metable进行原子操作
- --print(temp_metable_table + temp_table)
- --如果是这种方式的话,我们只能访问它的原子,也就是它的数据成员
- --[[setmetatable(temp_metable_table, {__index = temp_table} )
- print(temp_metable_table[1])
- print(temp_metable_table["lang"])--]]
- --如果是__newindex的话,我们可以访问原table,找到相关的key,除此之外,你还可以自己给原table添加数据成员
- setmetatable(temp_metable_table, {__newindex = temp_table} )
- temp_metable_table[5] = 100
- print(temp_metable_table[5])
- print(temp_table[5])
- 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,一个匿名函数
- -- body
- return 1000
- end
- w = Window.new({x = 10 ,y = 20})
- print(w.a) //在这里虽然没有a这个成员,但是会默认a为__index所绑定的function返回值作为a的值
- 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)
总结:
如果在元table中去找相应的操作,例如__index,__newindex等,如果有则直接访问,如果没有就新添加进元table中