网友问了一个问题,说对象A在内部可以修改HP.外部对象只能访问对象A的HP,不能修改.
这东西其实可以用__index和__newindex来实现.
__index指向对象A,这样就可以访问;
__newindex重写,修改hp的话,就禁止.就可以完成他的需求.
下面给出简单的代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30function cannotModifyHp(object) local proxy = {} local mt = { __index = object, __newindex = function(t,k,v) if k ~= "hp" then object[k] = v end end } setmetatable(proxy,mt) return proxy end object = {hp = 10,age = 11} function object.sethp(self,newhp) self.hp = newhp end o = cannotModifyHp(object) o.hp = 100 print(o.hp) o:sethp(111) print(o.hp) object:sethp(100) print(o.hp)
PS:
好长时间没写过lua了,都快忘了
最后
以上就是寂寞毛衣最近收集整理的关于[Lua]用__index/__newindex来限制访问的全部内容,更多相关[Lua]用__index/__newindex来限制访问内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复