Lua 只读属性

  • 创建Lua类型,可被实例化,可被继承
--创建一个类型对象
ClassType = {
	class,           --类型
	instance,		 --类型实例
}

--创建一个类型
function class(className,superClass)
	if superClass.classType ~= ClassType.class then
		assert(false, "类 才能够被继承")
	end
	local cls = {}
	cls.__className = className
	cls.__classType = ClassType.class
	cls.__index = cls
	if  superClass then
		setmetatable(cls,superClass)
	end 
	cls.new = function(self)
		local instance = setmetatable({},self)
		instance.__classType = ClassType.instance
		return instance
	end
	return cls
end
  • 创建具有只读属性的Lua类型 
  • 
    --创建一个类型对象 类型中有几个属性是只读的
    
    function classWithReadOnlyProperty(className,...)
    	local get = {}
    	local arg = { ... }
    	for i = 1,#arg do 
    		local key = arg[i]
    		get[key] = function(t)
    			return t[i]
    		end
    	end
    	local cls = {}
    	cls.__className = className
    	cls.__classType = ClassType.class
    	cls.__index =  function(self,key)
    		local f = rawget(cls,key)
    		if f then
    			return f
    		end
    		f =  rawget(get,key)
    		if f then
    			return f(self,key)
    		end
    	end
    	
    	cls.__newindex = function(self,key,value)
    		local f = rawget(get, key)
    		if f then
    			error("property is readonly:"..key)
    			return
    		end
    	end
    	
    	cls.new = function(self,...)
    		local instance = { ... }
    		setmetatable(instance,self)
    		instance.__classType = ClassType.instance
    		return instance
    	end
    	return cls
    end
    
    
    --创建一个vector 使x,y,z为只读的
    local vector = classWithReadOnlyProperty("Vector","x","y","z")
    
    local vec =  vector:new(1,2,3)
    
    print(vec.x)
    vec.x = 10
  • 应用场景:可用于生成Lua配置的数据对象 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值