http://blog.csdn.net/lqk1985/article/details/6415067
项目中有个公会对象,数据大部分存在data中,之前都是 u.data.point这样访问,太麻烦了。
于是通过设置__index 使之可以直接访问属性,u.point。
但是还是不能直接改属性,u.point = 4,所以再设置了__newindex。
在设置了setmetatable之后,不能直接给u添加新属性,因为设置了__newindex,新的属性将直接加到u.data中的。
- Union = {
- data = nil,
- dirty = nil,
- }
- --- 生成新的对象
- function Union:new(o)
- o = o or {}
- setmetatable(o,self)
- self.__index = self
- return o
- end
- --- 初始化Union数据
- function Union:init(data)
- self:initTable()
- self.data = data
- local meta = {}
- meta.__index = function (table, key)
- if Union[key] ~= nil then
- return Union[key]
- else
- return self.data[key]
- end
- end
- meta.__newindex = function(table,key, value)
- self.data[key] = value
- end
- setmetatable(self, meta)
- end
- function Union:initTable()
- if self.data == nil then
- self.data = {}
- end
- if self.dirty == nil then
- self.dirty = {}
- end
- end
- function Union:print()
- print(self.point, self.data.point)
- end
- function pt()
- print(data1.point, data2.point, u.point, u.data.point)
- end
- u = Union:new()
- data1 = {point = 3}
- data2 = {point = 103}
- u:init(data1)
- pt()
- u.point = 4
- pt()
- u.data = data2
- pt()
- u.point = 104
- pt()
通过修改__index和__newindex会获得不同的结果。
1.正确结果
- function Union:init(data)
- self:initTable()
- self.data = data
- local meta = {}
- meta.__index = function (table, key)
- if Union[key] ~= nil then
- return Union[key]
- else
- return self.data[key]
- end
- end
- meta.__newindex = function(table,key, value)
- self.data[key] = value
- end
- setmetatable(self, meta)
- end
3 103 3 3
4 103 4 4
4 103 103 103
4 104 104 104
2.错误的__newindex
- function Union:init(data)
- self:initTable()
- self.data = data
- local meta = {}
- meta.__index = function (table, key)
- if Union[key] ~= nil then
- return Union[key]
- else
- return self.data[key]
- end
- end
- meta.__newindex = self.data
- setmetatable(self, meta)
- end
3 103 3 3
4 103 4 4
4 103 103 103
104 103 103 103
3.错误的__index
- function Union:init(data)
- self:initTable()
- self.data = data
- local meta = {}
- meta.__index = function (table, key)
- if Union[key] ~= nil then
- return Union[key]
- else
- return data[key]
- end
- end
- meta.__newindex = function(table,key, value)
- self.data[key] = value
- end
- setmetatable(self, meta)
- end
3 103 3 3
4 103 4 4
4 103 4 103
4 104 4 104
这里影响程序的不同结果是upvalue导致的。
由于一般程序中有可能动态改data。所以建议用function设置__index和__newindex,尤其注意各个不同函数中self指向的是什么对象。
本文讨论了在项目中使用Lua脚本语言时,如何通过设置元表(metatable)来简化公会对象属性的访问,并解决了直接访问与修改属性时遇到的问题。详细解释了`__index`和`__newindex`元方法的作用,以及它们如何影响属性的读取与写入操作。通过示例代码展示了正确的实现方式,以及不当设置可能导致的属性行为变化。

702

被折叠的 条评论
为什么被折叠?



