lua - 元表Metatable与元方法__index、__newindex

1、 __index字段 对表访问
表中没有所查key值时,触发元表的__index方法

代码:

-- lua 元表

mymetatable = {}                      -- 元表
mytable = {}                          -- 普通表

print(mytable)
print(mymetatable)
print(getmetatable(mytable))
setmetatable(mytable,mymetatable)     -- 把 mymetatable 设为 mytable 的元表 
print(getmetatable(mytable))

print(mytable.x)

-- __index字段 对表访问
-- 表中没有所查key值时,触发元表的__index方法 

-- 如果__index包含一个表格,Lua会在表格中查找相应的键。 
-- mymetatable.__index = {x = 0, y = 1, width = 100, height = 200}
-- 如果__index包含一个函数的话,Lua就会调用那个函数,table和键会作为参数传递给函数。
mymetatable.__index = function(table, k)
                        -- body
                        return 1
                    end
print(mytable.x)
mytable.x = 2
print(mytable.x)

结果:

table: 00A2A188
table: 00A2A110
nil
table: 00A2A110
nil
1
2

2、__newindex字段 对表更新
当你给表的一个缺少的索引赋值,解释器就会查找__newindex 元方法:
注:如果存在则调用这个函数而不进行赋值操作。

代码:

__newindexTab = {}
mymetatable = {__newindex = __newindexTab}
mytable = {key1 = "value1"}
setmetatable(mytable, mymetatable)

print(mytable.key1)

mytable.newkey = "新值2"
print(mytable.newkey,__newindexTab.newkey)

mytable.key1 = "新值1"
print(mytable.key1,__newindexTab.key1)

结果:

value1
nil	新值2
新值1	nil

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值