baidu

[Lua]用__index/__newindex来限制访问

网友问了一个问题,说对象A在内部可以修改HP.外部对象只能访问对象A的HP,不能修改.

这东西其实可以用__index和__newindex来实现.

__index指向对象A,这样就可以访问;

__newindex重写,修改hp的话,就禁止.就可以完成他的需求.

下面给出简单的代码:

function 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了,都快忘了

posted @ 2011-09-27 14:16  egmkang  阅读(4601)  评论(2编辑  收藏  举报