加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
GetterSetter.lua 1.48 KB
一键复制 编辑 原始数据 按行查看 历史
Enrique García 提交于 2010-11-28 23:46 . updated comments
-----------------------------------------------------------------------------------
-- GetterSetter.lua
-- Enrique García ( enrique.garcia.cota [AT] gmail [DOT] com ) - 11 Aug 2010
-- Small mixin for classes with getters and setters
-----------------------------------------------------------------------------------
--[[ Usage:
require 'middleclass' -- or similar
require 'middleclass-extras.init' -- or 'middleclass-extras'
MyClass = class('MyClass')
MyClass:include(GetterSetter)
MyClass:getter('name', 'pete') -- default value
MyClass:setter('age')
MyClass:getterSetter('color', 'blue') -- default value
]]
assert(Object~=nil and class~=nil, 'MiddleClass not detected. Please require it before using GetterSetter')
GetterSetter = {}
function GetterSetter.getterFor(theClass, attr) return 'get' .. attr:gsub("^%l", string.upper) end
function GetterSetter.setterFor(theClass, attr) return 'set' .. attr:gsub("^%l", string.upper) end
function GetterSetter.getter(theClass, attributeName, defaultValue)
theClass[theClass:getterFor(attributeName)] = function(self)
if(self[attributeName]~=nil) then return self[attributeName] end
return defaultValue
end
end
function GetterSetter.setter(theClass, attributeName)
theClass[theClass:setterFor(attributeName)] = function(self, value) self[attributeName] = value end
end
function GetterSetter.getterSetter(theClass, attributeName, defaultValue)
theClass:getter(attributeName, defaultValue)
theClass:setter(attributeName)
end
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化