最近刚进公司不久,学习了脚本语言Lua,今天重新理解了下装饰器,感觉蛮简单的,就是把一个函数的功能稍微修饰下。
1、先看这个简单程序,求几个数的最大值。
local function my_max( ... )
return math.max( ... )
end
print(my_max(1,2,3))2、假设输入的值不是村数字的话,这时候应该报错,那该怎么实现呢
local function my_max( ... )
local input = { ... }
for key, value in pairs(input) do
if type(tonumber(value)) ~= 'number' then
print('invalid input at position ' .. tostring(key))
return 0
end
end
return math.max( ... )
end
print(my_max( 1,2,3 ))
print(my_max(1,'x',3))
输出结果:
3
invalid input at position 2
0
3、其实到上面我们就已经满足了需求,一般情况我没会写成如下重构代码:
local function isMyInputValid( ... )
local input = { ... }
for key, value in pairs(input) do
if type(tonumber(value)) ~= 'number' then
print('valid input at positon ' .. tostring(key))
return false
end
end
return true
end
local function my_max( ... )
if not isMyInputValid( ... ) then
return 0
end
return math.max( ... )
end
print(my_max( 1,2,3 ))
print(my_max(1,'x',3))
输出结果:
3
valid input at positon 2
04、这已经是我们可以接受范围,下面是一个以装饰器的思维来写的
local function dec(func)
local function _dec_in(...)
local input = { ... }
for key, value in pairs(input) do
if type(tonumber(value)) ~= 'number' then
print('invalid input at position ' .. tostring(key))
return 0
end
end
return func( ... )
end
return _dec_in
end
local function my_max( ... )
return math.max( ... )
end
my_max = dec(my_max)
print(my_max(1,2,3))
print(my_max(1,'x',3))
输出结果:
3
invalid input at position 2
0my_max = dec(my_max) 可以理解成 my_max = _dec_in,然后再往下调用
本文通过逐步展示如何在Lua中使用装饰器验证输入的有效性,解释了装饰器的基本概念及其应用。从基本函数到引入错误检查,再到使用装饰器模式进行重构,文章详细介绍了如何增强函数并简化代码。
2532

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



