環境
系統:Windows 10
引擎:Lua5.3.5
目的
根據closure的元機制給函數植入自定義檢測方案
實例
testFunc = function ()
print('testFunc')
end
print('------------before------------')
testFunc()
--[[
此處使用語法糖 local function checkFunc(param),
相當於先定義checkFunc這個變量,再賦值。
]]
local function checkFunc(param)
-- 此處爲檢測方案
local today = os.date('%d', os.time())
return today == '01'
end
local oldFunc = testFunc
testFunc = function()
--[[
以下的返回語句是用了“尾調用消除”機制,
此時調用的函數(oldFunc)不會在結束後,再回到此函數(testFunc),
相當於此函數結束後再調用另一函數。
就是說,不會在調用新函數時,進行壓棧操作,不會導致棧溢出。
]]
if checkFunc() then
return oldFunc()
else
return print('access failed')
end
end
print('------------after------------')
testFunc()
結果
上述例子,如果系統時間是本月1日,則
------------before------------
testFunc
------------after------------
testFunc
[Finished in 0.1s]
如果系統時間是本月9日,則
------------before------------
testFunc
------------after------------
access failed
[Finished in 0.1s]
以上簡單回顧。
參考資料:
《Lua程序設計(第二版)》第6章