在项目中经常会遇到很多重复代码,比如连接数据库,所以都会将这些代码写在一个lua文件中,供别的lua文件调用。但是该怎么做呢?
现有a.lua和b.lua,a.lua需要调用b.lua的test()函数。关键写法是在b.lua中:
local _M = {}
function _M.test()
ngx.say("hello test!")
end
return _M
需要一个_M表来将所有需要的函数装起来,然后在a.lua中这样调用:
local test = require("b")
if not test then
ngx.say("Failed to require b!")
return
end
test:test()
这个方法也是参考/usr/local/openresty/lualib/resty下的lua文件的写法,里面有很多值得参考的东西,想深入了解的可以去看看。