global variables from includes
Hi. I'm using the following nginx config:
worker_processes 1; location = /lua { content_by_lua_file 'main.lua'; }
The content of 'main.lua' file is:
require("include")
ngx.say(variable)
File 'include.lua' is required here, it's content (one line, global variable):
variable = "Test"
When I query the location, i see that after second request global variable from included file is gone: $ curl "127.0.0.1/lua" Test $ curl "127.0.0.1/lua" nil
But everything is fine when I turn code cache off.
nginx 1.5.11 lua-nginx-module-0.9.5rc2 luajit 2.0.2
@nvrmnd First of all, avoid using custom global Lua variables in the context of ngx_lua (and also for Lua in general) wherever possible. They are slow and might have bad side effects. Also, the global environment table in the context of content_by_lua has the same life time as the current request handler. See https://github.com/chaoslawful/lua-nginx-module#lua-variable-scope
@nvrmnd Only use require() for proper Lua modules that return a thing. That is,
local mymod = require "mymod"
local myvalue = mymod.myfield
Thank you very much for your quick answer! Loading includes this way works like a charm.
Consider it resolved.
Global variables are awesome and limitation on them is very sad, so:
require("include")
ngx.say(variable)
You can rewrite it to:
setfenv(loadfile('include.lua'), _G)()
ngx.say(variable)
Or even write helper:
include = function(path)
return setfenv(loadfile(path .. '.lua'), _G)()
end
And then just use include instead of require