最近刚进公司不久,学习了脚本语言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
0
4、这已经是我们可以接受范围,下面是一个以装饰器的思维来写的
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
0
my_max = dec(my_max) 可以理解成 my_max = _dec_in,然后再往下调用