lua-nginx-module
lua-nginx-module copied to clipboard
Using outer scope required modules inside an ngx.timer.at handler
Hello,
I've encountered an error which I understand the source to but unsure what's the best practice here.
I have the following example module respond.lua:
local ngx = require 'ngx'
local config = require 'config'
local required_module = require 'module_with_function'
local function handler(_, arg)
required_module.fn(arg)
end
local function main()
ngx.timer.at(0, handler, 'test')
ngx.status = config.code
ngx.say(config.response)
ngx.exit(config.code)
end
main()
This would result in attempt to index upvalue 'fn' error thrown from the handler function.
I deduced this is happening because the ngx.exit is called before the call to fn but this context sharing is unintuitive.
If I add a simple sleep before the call to ngx.exit it works just fine meaning the handler function does share the same context as the encapsulating module.
I resorted to adding another require inside the handler function but I would appreciate if there was a clear-cut answer on whether or not modules defined outside the ngx.timer.at handler function are available in it.
For clarification, lua_package_path is set up correctly.
OpenResty: version 1.25.3.1-2