lua 之__index/__newindex的理解

lua 之__index/__newindex的理解

  696人阅读  评论(0)  收藏  举报
  分类:
 
[plain]  view plain  copy
  1. --example:  
  2. local temp_table ={  
  3.     10,  
  4.     1,  
  5.     Index1 = "hello",  
  6.     Index2 = "world",  
  7.     Index3 = "lua",  
  8.     Index4 = "language",  
  9.     lang = "lua language",  
  10. }  
  11.   
  12. temp_table.__add = function(a, b) return 3 end  
  13.   
  14.   
  15. for _, Value in pairs(temp_table) do  
  16.     print(Value)  
  17. end  
  18.   
  19. local temp_metable_table = {  
  20.     Index1 = "temp_new_metable_Index1",  
  21.     Index2 = "temp_new_metable_Index2",  
  22.     Key = "temp_new_metable_Key_end",  
  23. }  
  24.   
  25.   
  26. for _, Metable_Value in pairs(temp_metable_table) do  
  27.     print(Metable_Value)  
  28. end  
  29. --只能访问temp_table的方法  
  30. --setmetatable(temp_metable_table,  temp_table) --如果setmetable 为这种方式的话,那么我不能够对metable进行原子操作  
  31. --print(temp_metable_table + temp_table)  
  32.   
  33. --如果是这种方式的话,我们只能访问它的原子,也就是它的数据成员  
  34. --[[setmetatable(temp_metable_table, {__index = temp_table} )   
  35.   
  36. print(temp_metable_table[1])  
  37. print(temp_metable_table["lang"])--]]  
  38.   
  39. --如果是__newindex的话,我们可以访问原table,找到相关的key,除此之外,你还可以自己给原table添加数据成员  
  40. setmetatable(temp_metable_table, {__newindex = temp_table} )   
  41. temp_metable_table[5] = 100  
  42. print(temp_metable_table[5])  
  43. print(temp_table[5])  



[plain]  view plain  copy
  1. Window = {}  
  2.   
  3. Window.prototype = {x = 0 ,y = 0 ,width = 100 ,height = 100,}  
  4. Window.mt = {}  
  5. function Window.new(o)  
  6.     setmetatable(o ,Window.mt)  
  7.     print(getmetatable(o))  
  8.     print(getmetatable(Window.mt))  
  9.     return o  
  10. end  
  11.   
  12. Window.mt.__index = function (t ,key) //由于__index 给赋予了funcion,一个匿名函数  
  13.     -- body  
  14.     return 1000  
  15. end  
  16.   
  17. w = Window.new({x = 10 ,y = 20})  
  18. print(w.a) //在这里虽然没有a这个成员,但是会默认a为__index所绑定的function返回值作为a的值  

[plain]  view plain  copy
  1. Window = {}  
  2. Window.mt = {}  
  3.   
  4. function Window.new(o)  
  5.     setmetatable(o ,Window.mt)  
  6.     return o  
  7. end  
  8. Window.mt.__index = function (t ,key)  
  9.     return 1000  
  10. end  
  11. Window.mt.__newindex = function (table ,key ,value)  
  12.     if key == "wangbin" then  
  13.         rawset(table ,"wangbin" ,"yes,i am")  
  14.     end  
  15. end  
  16. w = Window.new{x = 10 ,y = 20}  
  17. w.wangbin = "55"  
  18. print(w.wangbin)  

总结:

如果在元table中去找相应的操作,例如__index,__newindex等,如果有则直接访问,如果没有就新添加进元table中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值