--创建一个类型对象
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