lua之只读属性探讨

lua中如何实现类的只读属性呢?

这里我们可以用重写lua的元方法__newindex来模拟,参见如下:

--创建一个只读表
function readonly_Table(t)
    t = t or {}
    t.__index = t
    t.__newindex = function(table, key, value)
        print("Error : Attempt to update a read-only table! key = "..key)
    end
    return setmetatable({}, t)
end

MyClass = {
    a,
    b,
    --只读属性统一放在一个只读表readonly中
    readonly = readonly_Table({const = 100})
}

function MyClass:New(a, b)
    local o = {}
    setmetatable(o, self)
    self.__index = self
    o.a = a or 0
    o.b = b or 0
    return o
end

function MyClass:PrintInfo()
    print("a = "..self.a..", b = "..self.b..", const = "..self.readonly.const)
end

myclass = MyClass:New("abc", 126)
myclass:PrintInfo()
myclass.a = "def"
myclass.b = 999
myclass.readonly.const = 101
myclass:PrintInfo()

输出如下:

a = abc, b = 126, const = 100
Error : Attempt to update a read-only table! key = const
a = def, b = 999, const = 100

这里我们用到了__newindex元方法,lua中当本表找不到某个key时,会去找它的元表;如果元表存在,且元表的__newindex被重写了,在对key赋值时会自动走到这里,这样我们就可以做拦截来到达只读的效果

你可能感兴趣的:(lua,lua)